Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - safely render HTML in template
I am building a django web application where the user can submit text via a tinymce editor. For that task I use the django-tinymce extension. The question: Is it secure to render the HTML in the template using the safe filter like so ? : {{ richtext | safe }} If not, how can it be made safe ? -
Whats the difference between models and models.Model in django?(and similarly for forms and forms.Form )
I know that "models" is a module of package django.db, But why we inherit like class Foo(models.Model): while the all required fields like CharField, IntegerField, etc. are part of models, what does the subclass Model do here exactly? I am new to OOP and Django so any resources and answers are heavily appreciated and welcomed. -
Django: failed to run gunicorn
I try to run gunicorn but it failed I have install gunicorn in my virtual env (pip install gunicorn) cd intensetbm_app/intensetbm-etool gunicorn intenseTBM_eTool.wsgi:application my project architecture: envs intensetbm_app | intensetbm-etool | | intenseTBM_eTool | | | wsgi.py | | | settings.py | | | ... | | manage.py | | ... intensetbm_static wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intenseTBM_eTool.settings') application = get_wsgi_application() trace (partial): ... File "/home/test/intensetbm_app/intensetbm-etool/intenseTBM_eTool/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ModuleNotFoundError: No module named 'django' [2020-03-18 15:00:20 +0000] [43251] [INFO] Worker exiting (pid: 43251) [2020-03-18 15:00:20 +0000] [43248] [INFO] Shutting down: Master [2020-03-18 15:00:20 +0000] [43248] [INFO] Reason: Worker failed to boot. -
No URL to redirect to
I am trying to create a page where these parameters can be filled by the user. This code allows the data to be stored in mysql but does not show the saved data. And shows "ImproperlyConfigured at /public/about/ No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." MODELS class MedicalInfo(models.Model): BLOOD = ( ('A+', 'A+ Type'), ('B+', 'B+ Type'), ('AB+', 'AB+ Type'), ('O+', 'O+ Type'), ('A-', 'A- Type'), ('B-', 'B- Type'), ('AB-', 'AB- Type'), ('O-', 'O- Type'), ) @staticmethod def toBlood(key): for item in MedicalInfo.BLOOD: if item[0] == key: return item[1] return "None" patient = models.ForeignKey(User, on_delete=models.CASCADE, related_name="patiento") bloodType = models.CharField(max_length=10, choices=BLOOD) allergy = models.CharField(max_length=100) alzheimer = models.BooleanField() asthma = models.BooleanField() diabetes = models.BooleanField() stroke = models.BooleanField() comments = models.CharField(max_length=700) def __str__(self): return f'{self.user.username} Medinfo' def save(self): super().save() VIEWS.PY class MedinfoCreateView(LoginRequiredMixin, CreateView): template_name = 'all_users/public/medinfo.html' model = MedicalInfo fields = ['bloodType', 'allergy', 'alzheimer', 'asthma', 'diabetes', 'stroke', 'comments'] def form_valid(self, form): form.instance.patient = self.request.user return super().form_valid(form) HTML {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4"> Medinfo </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit"> … -
is there any reason i cannot register and then login user in the same function using Angular and Django?
Using Angular and Django. When a user registers I want them to be automatically logged in and sent to their homepage. I have a registerUser function in my UserApiComponent that looks like: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } console.log(this.user_cred) this.userauthcomponent.login(this.user_cred) } In my UserAuthComponent my login function is: login(user_cred){ this.authenticationService.login({'username': this.user_cred.username, 'password': this.user_cred.password}).subscribe( resp => { let response = resp; this.user_id = response.user_id this.router.navigateByUrl('/dashboard/'+this.user_id) }); } From my regular login page the login function works completely fine and I am able to login a user. From my registration page I am able to easily register a user. However, when I try to register AND login a user at one time so that the user does not have to login after registering I keep getting a bad request error: *core.js:6014 ERROR HttpErrorResponse {headers: HttpHeaders, status: 400, statusText: "Bad Request", url: "http://127.0.0.1:8000/users/api-token-auth/", ok: false, …} error: non_field_errors: ["Unable to log in with provided credentials."]* I know the credentials are correct because the console.log is outputting the correct info. I also tried just putting all the login logic inside of the registerUser function as follows: registerUser(){ this.userApiService.createuser(this.register).subscribe() this.user_cred = { username: this.register.username, password: this.register.password } this.authenticationService.login({'username': this.register.username, 'password': this.register.password}).subscribe( … -
Django: "django.contrib.gis.gdal.prototypes.ds" crashes with "attributeerror: symbol not found"
Running the latest Django (3.0.4) I am now getting this: File "[...]site-packages/django/contrib/gis/gdal/driver.py", line 5, in <module> from django.contrib.gis.gdal.prototypes import ds as vcapi, raster as rcapi File "[...]site-packages/django/contrib/gis/gdal/prototypes/ds.py", line 71, in <module> get_field_as_integer64 = int64_output(lgdal.OGR_F_GetFieldAsInteger64, [c_void_p, c_int]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 361, in __getattr__ func = self.__getitem__(name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/ctypes/__init__.py", line 366, in __getitem__ func = self._FuncPtr((name_or_ordinal, self)) AttributeError: dlsym(0x101667060, OGR_F_GetFieldAsInteger64): symbol not found My Observations: I have [ellided] the path names which refer to Django in my virtual-environment. I observe that the module that is actually crashing is in /Library/Frameworks/Python.framework/ ... this on Macintosh OS/X Catalina. The version of Python that is installed on this computer is 3.6.4. (The version on the hosting service is considerably older ... 3.4.) Is this, as I suspect, a problem with the Python installation on this computer? (The most recent version that can be installed here is 3.7.7.) -
Django ForeignKey for multiple models with reverse relation
I'm currently working on a project where I have to assign values for certain instances while not affecting them. To give an example let's assume its a multi-service shop and we have a shopping cart where I have to put an Item order so I need ForeignKey to item ForeignKey to cart quantity the item but the item can be either product or service and cart can be a normal or special (two different models in both cases). I know how to achieve it but the thing that I couldn't obtain is the ability to call the item_order from for example product instance that its linked to. I'd be glad if anyone can either help me achieve the goal or show me another approach on the problem. Here is the exemplary code that hasn't given me the ability for revese access of item_order # https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#generic-relations class ValueBox(models.Model): class Meta: verbose_name_plural = 'ValueBoxes' # target is product or product group - can be later on expanded for future models item_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='target_content_type') item_id = models.PositiveIntegerField() item_object = fields.GenericForeignKey('target_type', 'target_id') # input is for example sales plan or brass plan its necessary to make it # flexible as there are … -
.NoReverseMatch: Reverse for 'author-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/author/(?P<pk>[0-9]+)$']
Many people have already ask similar question to this, but I still cannot figure out the solution unfortunately. I am doing a django tutorial from https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Tutorial_local_library_website . I compared my code with their's on Github but I do not see the difference. The current state of my code is here https://github.com/diveki/webdev/tree/master/django_projects/locallibrary it works well except for showing the details of the Author model. The error message I get is: django.urls.exceptions.NoReverseMatch: Reverse for 'author-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/author/(?P<pk>[0-9]+)$'] . I do not copy here all the code I wrote for this (unless you need it), but here is my models.py, urls.py from catalog, the relevant code from views.py and the templates: Part of my catalog/models.py: from django.db import models from django.urls import reverse # Used to generate URLs by reversing the URL patterns import uuid # Required for unique book instances class Author(models.Model): """Model representing an author.""" first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) date_of_death = models.DateField('died', null=True, blank=True) class Meta: ordering = ['last_name', 'first_name'] def get_absolute_url(self): """Returns the url to access a particular author instance.""" return reverse('author-detail', args=[str(self.id)]) def __str__(self): """String for representing the Model object.""" return '{0}, {1}'.format(self.last_name, self.first_name) catalog/urls.py: from … -
How to change multiple elements innerHTML using setinterval?
I'm working on certain app and I need to create kind of count down for each element. Unfortunately when I', passing the element to my function it does not work. Neverthless if I change the function a bit and just replace the element's innerHTML out of the setInterval it starts working. I'm totally out of any idea now. Appreciate for help :) const timeout is the element. const json_content = json_reader(reserved) for(x=0;x<json_content["key"].length;x++){ var tds = document.querySelectorAll(".display_content table td") for(let td of tds){ new Vue({ delimiters: ['[[', ']]'], el:td, data: { display: "test", seats_number: "0", }, methods:{ test(){ console.log("elo") } }, created: ()=>{ const td_date = td.innerText if(td_date.includes(json_content["key"][x])){ const td_hour = td.nextElementSibling const json_hour = json_content["value"][x]["times"] if(Object.keys(json_hour).includes(td_hour.innerText)){ const seats = json_content["value"][x]["times"][td_hour.innerText] const td_seat = td_hour.nextElementSibling const timeout = td_seat.nextElementSibling const seats_array = [] seats.forEach(element => { const seat_json = json_reader(element) seats_array.push(seat_json["key"]+":"+seat_json["value"]) }); this.seats_number = seats.length td_seat.innerHTML = "<span onclick='display_seats(this.nextSibling)'>"+[[this.seats_number]]+"</span>"+"<span class='seats' value='"+seats_array+"'></span>" counter(timeout) } } } }) } } and counter function: function counter(element){ var t = 10 setInterval(()=>{ element.innerHTML = String(t) t -= 1 },1000) -
Invalid block tag on line 66: 'endblock', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
Why is it giving me this strange error: Did you forget to register or load this tag? it was working fine but when i did some changes in this code it started this error... i was going through question related to this issue but could not find the solution.... <div class="container"> <div class="row"> <div class="pagination"> {% for item in post.object_list %} <!-- {% for item in post %}--> <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{item.intro}}</p> <!-- href={% url 'bicep' %}--> <a href="blog_detail/{{item.post_id}}" class="btn btn-primary">read more...</a> <!-- <a href="{% url 'blog_detail/pk' pk=item.post_id %}" class="btn btn-primary">read more...</a>--> </div> </div> {% if forloop.counter|divisibleby:4 %} </div> {% endif %} {% endfor %} -
Reset password after first successful login
I am building an web application using existing Auth features in Django where admin create user profile with username and password. Admin created user name and password will be given to user to login. So for security reasons I need to ask user to reset password (given by admin) after user's first successful login. To reset password, I will be displaying template where user should be entering only new password and new password again for confirmation. This new password will be updated in sqlite database. So whenever admin changes the users password. I need to ask users to reset password after first successful login. Here are the implementation I have done. models.py: Here I set boolean flag profile.force_password_change to TRUE when new user created. But profile.force_password_change is not setting to TRUE whenever existing user password changed or new user created. middleware.py: Whenever force_password_change set to TRUE, then I use middle-ware to redirect to change password view. I have written below code to set profile.force_password_change to TRUE whenever new user is created or user password is changed by admin. class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) force_password_change = models.BooleanField(default=False) def create_user_profile_signal(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) pass def password_change_signal(sender, instance, **kwargs): … -
django cache changed by the database status
I have viewset with cache like this on off by changing False -> True def maybe_decorate(condition, decorator): return decorator if condition else lambda x: x class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all().order_by('id') serializer_class = TweetSerializer filter_class = TweetFilter @method_decorator(cache_page(60*60*2)) @method_decorator(vary_on_cookie) @maybe_decorate(False,method_decorator(cache_page(60*60*2))) @maybe_decorate(False,method_decorator(vary_on_cookie)) Then now I have one idea. I can get the update time here SELECT UPDATE_TIME FROM information_schema.tables WHERE table_schema = DATABASE() and TABLE_NAME = 'tweet' I want to check this variable and switch on / off cache Is it possible?? or my idea is good practice?? -
DRF Serializer update method always has empty validated_data object when using PATCH + multipart/form-data
I've been banging my head about this one for a bit as I seem to be missing something obvious in this issue. First off, I have multiple parsers loaded for my DRF setup in settings.py: REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ), } Given the presence of the MultiPartParser I would presume that DRF should be parsing the body correctly. However in my ModelSerializer I am overriding the update handler to handle the files and attach them to the model, however all the fields are empty when I interate through them, even the basic ones like 'id' - however I know it must be interpreting the data, because the correct instance is loaded every time, in this case it's the user that is being updated. class UserSerializer(ModelSerializer): """ Serializer for the Logged in User """ avatar = VersatileImageFieldSerializer( sizes='member_avatar' ) background = VersatileImageFieldSerializer( sizes='member_background' ) class Meta: model = Member fields = ( 'id', 'email', 'username', 'language', 'bio', 'location', 'homepage', 'avatar', 'is_staff', 'groups', 'background', 'created', 'edited', 'last_login', 'slug', 'signature' ) read_only_fields = ['created', 'edited', 'slug'] def update(self, instance, validated_data): """ Update the user. :param instance: user instance :param validated_data: validated form data :return updated user """ updated_fields = … -
How can I create post?
This is my fist django project, so I have some problems to use form. I searched how to create post but I have problem. I don't know why posting is not work. Please help me... I want to save POST and Image FILE. views.py ` @login_required() def postFind(request): if request == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit = False) post.menu = True post.pub_date = timezone.datetime.now() post.up_date = timezone.datetime.now() post.user = request.user post.save() return HttpResponseRedirect(reverse('website:postCheck', args=(post.id))) else: form = PostForm() return render(request, 'postFind.html', {'form' : form}) ` postFind.html {% if user.is_authenticated %} <div class="form"> <form class="post-form" method="post" enctype="multipart/form-data" action="{% url 'website:postFind' %}"> {% csrf_token %} <div class="wrapper"> <div class="box"> <div class="js--image-preview"></div> <div class="upload-options"> <label> {{ form.image }} </label> </div> </div> <p id="info">Species</p> {{ form.species }} <p id="info">Location</p> {{ form.location }} <p id="info">Date</p> {{ form.date }} <p id="info">Feature</p> {{ form.feature }} <button type="submit" class="btn btn-default">Submit</button> <a class="btn btn-default" href="{% url 'website:homePost' %}" role="button" id="button">Cancel</a> </form> </div> {% endif %} form.py ` class PostForm(ModelForm): class Meta: model = Post fields = ['image', 'species', 'location', 'date', 'feature'] ` -
How can I use React.lazy with Django and Webpack 4?
I am building app with django on the backend and react on the frontend. I would like to use React.lazy, but I have some problems with Django, because it can not find other bundels except main.js which I have added to index.html template. This is my Webpack configuration: const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.js', output: { path: __dirname + '/dist', filename: 'index_bundle.js' }, plugins: [ new HtmlWebpackPlugin() ], module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\.css$/i, use: ['style-loader', 'css-loader'], }, { test: /\.(png|jpe?g|gif)$/i, use: [ { loader: 'file-loader', }, ], }, ] } }; Django view: def index(request): return render(request, 'frontend/index.html') index.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'frontend/favicon.ico' %}" type="image/x-icon"> <link href="https://fonts.googleapis.com/css?family=Oswald&display=swap" rel="stylesheet"> <title></title> <link rel="stylesheet" href="{% static 'frontend/bootstrap.min.css' %}" /> </head> <body> <div id="app"> <!-- React will load here --> </div> </body> <script src="{% static "frontend/main.js" %}"></script> </html> React app: class App extends Component { componentDidMount() { store.dispatch(loadUser()); } render() { return ( <Provider store={store}> <AppRouter /> </Provider> ); } } and AppRouter const AsyncHome = React.lazy(() => import(/* webpackChunkName: "Home" */ … -
uploding image into database using modelforms in django
I'm trying to upload image with model form using user template into database and it didn't work but it does with admin page , I'm getting all other data except the image , the code is below I know its not great but I'm getting frustrated and I hope someone could help especially with my views.py Thank you so much. Thank you in advance! Models.py import os, random from django.db import models from django.contrib.auth.models import User from django.db.models.signals import pre_save from django.utils import timezone as tz from django.urls import reverse from .utils import unique_slug_generator def get_filename_and_ext(filename): base_name = os.path.basename(filename) name ,ext = os.path.splitext(base_name) return name,ext def upload_file_to(instance, filename): new_filename = random.randint(1,29494923) name, ext = get_filename_and_ext( final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext) return 'post/{new_filename}/{final_filename}'.format(new_filename=new_filename, final_filename=final_filename) class Post(models.Model): title = models.CharField(max_length=20) slug = models.SlugField(blank=True, unique=True) content = models.TextField() time = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to=upload_file_to, null=True, blank=True) auther = models.ForeignKey(User) def get_absolute_url(self): return reverse("posts:detail",kwargs={"slug":self.slug}) objects = AccountManager() def __str__(self): return self.title def post_pre_save_reciver(sender, instance, *arg, **kwargs): if not instance.slug : instance.slug = unique_slug_generator(instance) pre_save.connect(post_pre_save_reciver, sender = Post) forms.py from django import forms from django.contrib.auth import get_user_model # from . import models from .models import upload_file_to, get_filename_and_ext, Post, Comment from .utils import unique_slug_generator class post_form(forms.ModelForm): class … -
django.template.exceptions.TemplateDoesNotExist: registration/login.html
here's my files: views.py from django.shortcuts import render from django.urls import reverse_lazy from . import forms from django.views.generic import CreateView from django.views.generic import TemplateView class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "webportal/signup.html" class HelloPage(TemplateView): template_name = "hello.html" 2.apps urls.py: from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = "webportal" urlpatterns = [ path("logout/", auth_views.LogoutView.as_view(), name="logout"), path("", views.SignUp.as_view(), name="signup"), path( "login/", auth_views.LoginView.as_view(template_name="webportal/login.html"), name="login", ), ] 3.models.py: from django.db import models from django.contrib import auth class User(auth.models.User, auth.models.PermissionsMixin): """ this is account User model""" def __str__(self): return "@{}".format(self.username) 4.forms.py: from django.db import models from django.contrib import auth class User(auth.models.User, auth.models.PermissionsMixin): """ this is account User model""" def __str__(self): return "@{}".format(self.username) 5.templates->webportal(myapp's name)->1.login.html , {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <div class="container"> <h1>Login In</h1> <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Login" class="btn btn-default" /> </form> </div> {% endblock content %} 2.signup.html {% extends "base.html" %} {% load bootstrap3 %} {% block content %} <div class="container"> <h1>Sign Up</h1> <form method="POST" action="{% url 'webportal:login' %}"> {% csrf_token %}{% bootstrap_form form %} <input type="submit" value="Sign Up" class="btn btn-default" /> </form> </div> {% endblock content %} … -
Django order by query in foreign key cases
I do have two tables such that, class A(BaseModel): name = models.CharField(...) class B(BaseModel): a = models.ForeignKey(A, on_delete=models.CASCADE) val = models.IntegerField(blank=True, null=True) a = A.objects.all().oreder_by("b__val") Whenever I use order by query, getting repeated instances with different val. But i wanna get only one row from the B model. Optimized query?? NOTE: Using MySQL. -
Django template tags loop in condition for comm seperation
This is my current condtion: {% for d in datalist %} <span class="bold">{{ d }}, </span> {% endfor %} For example, in datalist, the datalist is a queryset, i have these ['t;, 'b', 'c'] I need to show this data like thise t,b,c. in the last item, there should be a fullstop/dot, and after each item, there should comma Can anyone help me to fix this? -
saving template for specific user
Is that possible to save a certain template content to a certain user? I want to display diffrent content on the right side of the image dependent of user's choices.The whole view is coded in JS and HTML The code I want to be unique <div class="home-wrapper home-wrapper-second"> <div class="player-on-map toplaner"> <img class='img-on-map' src="{% static 'images/ago/img1.png' %}" alt="portrait-on-map"> <span name='n' class="nickname">Szygenda</span> </div> <div class="player-on-map jungler"> <img class='img-on-map' src="{% static 'images/ago/img2.png' %}" alt="portrait-on-map"> <span class="nickname">Zanzarah</span> </div> <div class="player-on-map midlaner"> <img class='img-on-map' src="{% static 'images/ago/img3.png' %}" alt="portrait-on-map"> <span class="nickname">Czekolad</span> </div> <div class="player-on-map botlaner"> <img class='img-on-map' src="{% static 'images/ago/img4.png' %}" alt="portrait-on-map"> <span class="nickname">Woolite</span> </div> <div class="player-on-map support"> <img class='img-on-map' src="{% static 'images/ago/img5.png' %}" alt="portrait-on-map"> <span class="nickname">Mystqiues</span> </div> </div> ```[![enter image description here][1]][1] [1]: https://i.stack.imgur.com/8n9Wv.jpg -
GenericViewSet------TypeError: 'method' object is not iterable
Hello I'm new to Django RestFramework, I'm trying to implement Genericviewset but I keep getting this error " TypeError: 'method' object is not iterable " my code is as follows views.py---- class exampleviewset(viewsets.GenericViewSet, mixins.ListModelMixin): serializer_class=exampleSerializer queryset=example.objects.all What might be the reason for this error? -
How can IPAddressField error message be changed
first of all, Its not duplicated Im using djangorestframework==3.11.0 django==3.0.3 I have changed the CharField Error_message easily but when im trying to change the error message for the IPAddressField class InterfaceSerializer(serializers.Serializer): ip_address = serializers.IPAddressField(protocol="IPv4", required=False, allow_blank=True, error_messages={'invalid': 'test fail'}, ) but the result is always {"error_message": { "ip_address": [ "Enter a valid IPv4 address." ]}} and response is 2020-03-18 13:13:12,878 : ERROR : response : {'error_message': {'ip_address': [ErrorDetail(string='Enter a valid IPv4 address.', code='invalid')]}} -
Huey; Doesn't run tasks in one Django App
i have an app called "tickets", it's in the settings file, can be imported correctly. INSTALLED_APPS = [ ... "huey.contrib.djhuey", "core", "telefon", "termine", "tickets", ... ] I am running Huey for background tasks and it does run all tasks in two other apps, just not in the app "tickets". Here is the module "helpers" in the app tickets: from huey import crontab from huey.contrib.djhuey import db_periodic_task, periodic_task @periodic_task(crontab(minute="*/1")) def checkForRunningHuey(): logger.debug("Huey did run at {pendulum.now()}") @db_periodic_task(crontab(minute="*/5")) def getKissTickets(): site_settings = Setting.load() if not site_settings.last_update_tickets: soy, now = getThisYear site_settings.last_update_tickets = soy site_settings.save() site_settings = Setting.load() ... And here is my Huey Configuration: HUEY = { "huey_class": "huey.RedisHuey", # Huey implementation to use. "name": "Huey", # Use db name for huey. "results": False, # Store return values of tasks. "store_none": False, # If a task returns None, do not save to results. "immediate": False, # If DEBUG=True, run synchronously. "utc": True, # Use UTC for all times internally. "blocking": True, # Perform blocking pop rather than poll Redis. "connection": { "host": "192.168.x.xxx", "port": 6379, "db": 0, "connection_pool": None, # Definitely you should use pooling! "read_timeout": 1, # If not polling (blocking pop), use timeout. "url": None, # Allow Redis config via … -
Django OperationalError: table sampleapp_userprofile has no column named email
Git Repo I'm a beginner in the Django. I tried to implement JWT inside Python but when I add a new user I get an error, which is as follows. django.db.utils.OperationalError: table sampleapp_userprofile has no column named email I have created the email field and also put the default value in the email field, and I still get this error .. I have provided the git repository and given some code below, please help. models.py from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): email = models.EmailField(verbose_name="email",max_length=60, unique=True,default='') username = models.CharField(max_length=30,default='Null') password = models.CharField(verbose_name='password',max_length=16) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) objects = MyAccountManager() USERNAME_FIELD = 'username' EmailField = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email views.py from django.shortcuts import render from rest_framework.views import APIView from rest_framework.response import Response from … -
Collectstatic copies my new css file, but doesn’t get served
I collectstatic and see my style.css file copied properly. The browser is serving a style.css file with a hash in the name. It is an old css file. How do I get collectstatic to work with my new css file. I’m using Django 2.2.