Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSRF Breaks Django Server
Django 2.1.4, Python 3.7, Django Test Server When I send an Ajax request that includes a CSRF token to an invalid URL and then follow it up with any request afterwards, body data from the first Ajax request is prepended to the next request, making the request invalid. [01/Aug/2019 16:57:27] "POST /profile/add_favorite HTTP/1.1" 404 4132 Forbidden (CSRF token missing or incorrect.): / [01/Aug/2019 16:57:50] "title=Video+TitleGET / HTTP/1.1" 403 2513 Notice that second line, the "title" parameter is from the previous request. It is possible to send requests such that middle "Forbidden (CSRF token missing or incorrect.):" is not present but the invalid processing is still done by the server. If that second request is coming from a new browser window, the “invalid CSRF” page is returned even though it is the first time opening the home page of my site from a fresh window. The following requests are then processed correctly assuming they’re valid. The problem occurs any time a request with an csrf token header is sent to an invalid URL. So, if I don't include the CSRF token in a header my server works fine. Not sure how to solve this other than removing CSRF altogether which is … -
can't use nextjs as frontend and django and backend
So I was starting a project that I'll probably use Next and Django in. and I know how to integrate client-side react with Django but it turned out there's no actual way to run nextjs with django because of next use express. so I decided to make a two different apps, django api, and next frontend but i cant decide whether i can put both on the same VPS and run them with Nginx or should I deploy them separately. what's more efficient? -
Updating data in Database from Django form
I'm trying to add a form to alter some data in my database. Basically, when the user submits the button, the new value should update the old value. This is what the template looks like: {% for row in mydb %} <form method="post" novalidate> {% csrf_token %} {% include 'main/includes/bs4_form.html' with form=form3 %} {{row.firstfield}} {{row.secondfield}} <button name="button3" type="submit" class="btn btn-danger style="background-color: red;">CANCEL</button></td> </form> {% endfor %} The for statements is to display each row of the data in my table in a single line. Near each line, there is a submit button. When this button is clicked, the field secondfield is updated with the value New Value, as you can see in my form. Thi is the part of the view involved: def myview(request, tvticker): row = mydb.objects if request.method == 'POST': ... if 'button3' in request.POST: form3 = form = UpdateForm(request.POST) if form3.is_valid(): profile = form.save(commit=False) profile.save() messages.success(request, f"Success") ... render(request, "main/mytemplate.html", context={'row': row,}) And here is the form: class UpdateForm(forms.ModelForm): SomeField = forms.CharField() class Meta: model = MyModel fields = ("SomeField",) def save(self, commit=True): send = super(UpdateForm, self).save(commit=False) send.secondfield = 'New Value' if commit: send.save() return send My actual code it's not working, is seems to send a … -
Django: How to convert url to path-urlpatterns in urls.py
So I'm having a small problem cleaning up a bit of code for url paths in an old django project. Previously I was importing a Newsletter app to the master application using the old url pattern like so... urls.py url(r'^newsletter/', include('newsletters.urls', app_name="newsletter", namespace="newsletter")) Now I'd like to bring it into an array of urlpatterns. All other patterns are working as intended aside from this one. urls.py ... from django.urls import path, include path('admin/', admin.site.urls), path('articles/', include('articles.urls')), path('', views.main, name='main'), path('register/', sub_views.register, name="register"), path('summernote/', include('django_summernote.urls')), ... I think it has something to do with the views.py file, and how I'm supposed to bring it in, so I'll include it here. from django.shortcuts import render from .models import Newsletter from .forms import NewsletterUserSignUpForm # Create your views here. def newsletter_signup(request): form = NewsletterUserSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if Newsletter.object.filter(email=instance.email).exists(): print("Sorry. This email already exists") else: instance.save() context = { "form": form, } template = "newsletters/sign_up.html" return render(request, template, context) def newsletter_unsubscribe(request): form = NewsletterSignUpForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) if Newsletter.objects.filter(email=instance.email).exists(): Newsletter.objects.filter(email=instance.email).delete() else: print("We did not find your email address") context = { "form": form, } template = "newsletters/sign_up.html" return render(request, template, context) It's been quite some … -
full_clean() missing while Creating a related object in Django
I have two models my django app, on model is a foreign key in the other. My two models are : User and Attribute. each user has lot of attributes I am using generic views to create,update and delete my models. for my first model (User) everything works fine. But when i want to to create rows for my second models i get this error :full_clean() missing 1 required positional argument: 'self' This is my view : class AttributeCreate(CreateView): form_class = AttributeForm template_name = 'myapp/attribute_form.html' def get_form_kwargs(self): kwargs = super(AttributeCreate, self).get_form_kwargs() if kwargs['instance'] is None: kwargs['instance'] = Attribute kwargs['instance'].userid = self.kwargs['pk'] return kwargs And this is my form.py class AttributeForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(AttributeForm, self).__init__(*args, **kwargs) # if userid: for field_name, field in self.fields.items(): field.widget.attrs['class'] = 'form-control' class Meta: model = Attribute exclude = ['userid'] I am using Django 2.1, by the way, I've developed this use case in Django 1.9 and it works. -
Django Error 500 related to staticfiles when DEBUG = False
Here is my settings.py: import os import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'secret_key' DEBUG = False ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'corsheaders', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp', 'rest_framework', 'django_celery_beat' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', # CORS support [keep load position] 'django.middleware.common.CommonMiddleware', #'django.middleware.cache.UpdateCacheMiddleware', #'django.middleware.common.CommonMiddleware', #'django.middleware.cache.FetchFromCacheMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", "http://127.0.0.1:8080", "http://localhost:80" ] CSRF_TRUSTED_ORIGINS = [ 'http://localhost:8080', ] ROOT_URLCONF = 'django_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'django_backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'name', 'USER': 'user', 'PASSWORD': "pw", 'HOST': 'localhost', 'PORT': '5432' } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) CELERY_BROKER_URL = 'redis://url:port' CELERY_RESULT_BACKEND = 'redis://url:port' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = TIME_ZONE LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, 'console':{ 'level': 'DEBUG', … -
Is there a django package that sends desktop notifications with sound
I am working on a django application that consumes data from other systems and creates notifications on the users interface. I am currently using django-notifications for this although it does not have an option for desktop notifications. I have also searched and can't seem to find anything to use. I would like to implement desktop notifications(with sound) so that even if the user is not on that application's page, they will get notified. Is there a django package that does this kind of thing. Thanks in advance for the help. -
Djange Queryset .annotate - Add 45 days to a date field
I want to display my_date + 345 days using Django .annotate. In the code below, date_plus_1=ExtractYear('my_date')+1, works fine to give me a the year plus one, but I want the date plus 345 days. CODE: .annotate( date_plus_1=ExtractYear('my_date')+1, #date_plus_345=('my_date' + timedelta(days=345)), ) When I remove the # (in the code), my page will not generate. After searching around, I also tried this: date_plus_345=ExpressionWrapper(F('my_date') + timedelta(days=345)), but that did not work either. What is the correct way to use timedelta within .annotate? -
What's the fobi form url? And how do I embed it in another template?
I'm using Django-fobi, and I don't know how to do the following: 1) get a url for sharing the form without allowing a user to edit the form 2) include the form in another existing template Any help is appreciated. -
How to set filter to generate a custom EXCELl with DRF renderer-xlsx
Good afternoon I have the following query, I am using the library Renderer-xlsx of DRF to generate an excel, I download it when passing the respective url, the question is that I want to apply filter to this excel, so that I do not download everything that is in the database, but what I I indicated in the filter. In summary: I have a download button in the frontend (ANGULAR), I press it, I indicate the filter that for example in the excel only comes the records that meet this condition (EquipoOriggen = C65CAN01) I pass it as a request and return get the excel As you see download, but all the records, and I need it with filter My serializer class InterfaceSerializer(serializers.ModelSerializer): # Las siguientes lineas me permiten agregan campos de otros modelos al modelo en cuestion que estoty serializando a traves de llaves foraneas. #Se le agrega la propiedad de read_only=True para que el campo no sea editable. EquipoOrigen = serializers.CharField(source='id_EquipoOrigen.nombre',read_only=True) PuertoOrigen = serializers.CharField(source='id_PuertoOrigen.nombre',read_only=True) LocalidadOrigen=serializers.CharField(source='id_EquipoOrigen.localidad',read_only=True) CategoriaOrigen=serializers.CharField(source='id_EquipoOrigen.categoria',read_only=True) EquipoDestino = serializers.CharField(source='id_EquipoDestino.nombre',read_only=True) PuertoDestino = serializers.CharField(source='id_PuertoDestino.nombre',read_only=True) LocalidadDestino=serializers.CharField(source='id_EquipoDestino.localidad',read_only=True) CategoriaDestino=serializers.CharField(source='id_EquipoDestino.categoria',read_only=True) Vendedor=serializers.CharField(source='id_EquipoOrigen.vendedor',read_only=True) class Meta: model=Interfaces fields=('id_interface','id_EquipoOrigen','EquipoOrigen','id_PuertoOrigen','PuertoOrigen','LocalidadOrigen','CategoriaOrigen','Vendedor','estatus','etiqueta_prtg','grupo','if_index','bw','bw_al','id_prtg','ospf','description','id_EquipoDestino','EquipoDestino','id_PuertoDestino','PuertoDestino','LocalidadDestino','CategoriaDestino','ultima_actualizacion',) class PostPageNumberPagination(PageNumberPagination): page_size=10 page_size_query_param = 'page_size' max_page_size = 1000 #Funcion Para El Filtro del Modelo Interfaces. class InterfacesFilter(filters.FilterSet): EquipoOrigen=filters.CharFilter(field_name='id_EquipoOrigen__nombre',lookup_expr='contains') … -
Java rest client framework for Django QuerySet syntax
There are a bunch of public rest APIs built with Django which expose Django's QuerySet filtering and field selecting features For example: https://api.hubapi.com/content/api/v2/pages?hapikey=demo&translated_from_id__is_null&name__icontains=test&order=created&property=id&property=name&property=current_state&property=translated_content where: &name__icontains=test means case insensitive lookup by the field name which value contains subsgtring test &translated_from_id__is_null means that field translated_from_id is not null &property=id&property=name&property=current_state means that only these declared properties should be returned Other examples: https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_properties__full_mwt__range=200,500 https://www.ebi.ac.uk/chembl/api/data/molecule?molecule_chembl_id__in=CHEMBL25,CHEMBL941,CHEMBL1000 Is there any Java framework which provides high-level abstractions above this query syntax? -
Python/Django Saving m2m with Through
The code below is stripped down to illustrate the issue. While there are things that you may want to say "why would you do this anyway", there is probably a reason in the larger context :) Here is my view: class SubmissionCreate(CreateView): model = Submission fields = '__all__' template_name_suffix = '_create_form' success_url = '/' Here is the relevant models.py code: def custom_filename(instance, filename): author = instance.publishers[0] return 'papers/{0}.pdf'.format(author.pseudonum) class Submission(models.Model): name = models.CharField( max_length=200, blank=False ) upload = models.FileField( blank=True, upload_to=custom_filename ) publishers = models.ManyToManyField( 'Publisher', blank=False, related_name='publisher_of', through='SubmissionPublisher' ) class Publisher(models.Model): user = models.ForeignKey( User, blank=False, on_delete=models.CASCADE ) pseudonym = models.CharField( max_length=200, blank=False ) class SubmissionPublisher(models.Model): publisher = models.ForeignKey( 'Publisher', blank=False, on_delete=models.CASCADE ) submission = models.ForeignKey( 'Submission', blank=False, on_delete=models.CASCADE ) The problem is in the custom_filename, because I need the first publisher from the instance to generate the filename. The Submission is not yet saved when the SubmissionPublisher needs it to be saved. What would the best way to do this be. Hopefully I have made sense here. Thanks for any help! -
how does django channels knows that a client has disconnected?
I fear that a client loses connection abruptly and get disconnected without leaving any info to the backend. If this happens, will the socket keep active? -
Django-filters is it possible to skip values that aren't a choice in the filter?
I want to filter events by who hosts them in my API. NOTE: Hosts do not have their own tables. They are just a field on an event. I want to be able to send multiple values and grab all their events. So for instance if I query like this api/events?host=ashley&host=bob, it will return both bob's and ashley's events. But if a user enters in another name that doesn't have an event, I'd still like it to return the other hosts events. Is that possible, to skip non existent choices? I've been using the django-filter AllValuesMultipleFilter function to filter all the hosts. Is there a way to skip over a choice if it doesn't exist? class EventFilter(dr_filters.FilterSet): after_start_date = dr_filters.DateTimeFilter(field_name="start_date", lookup_expr="gte") before_end_date = dr_filters.DateTimeFilter(field_name="end_date", lookup_expr="lte") category = dr_filters.AllValuesFilter(field_name="categories__name") venue = dr_filters.AllValuesFilter(field_name="venue__name") status = dr_filters.AllValuesMultipleFilter(field_name="event_status") host = dr_filters.AllValuesMultipleFilter(field_name="host") class Meta: model = Event fields = ( "after_start_date", "before_end_date", "internal_only", "category", "venue", "status", "host" ) # Define ViewSets class EventViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = EventSerializer filter_backends = (filters.SearchFilter, dr_filters.DjangoFilterBackend,) filter_class = EventFilter search_fields = ("name",) ordering_fields = ("name", "start_date", "venue",) def get_queryset(self): qs = Event.objects.filter(start_date__gte=timezone.now()) qs = qs.order_by("start_date") return qs { "host": [ "Select a valid choice. emma is not one of the available … -
Dynamically Adding a Field to Django modelformset ManagementForm data is missing or has been tampered with
In my app, I have to dynamically add a field to the modelformset in the init method of the custom modelformset by extending BaseModelFormSet. class BaseInvoiceFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): excluded_fields = kwargs.pop('excluded_fields', None) super(BaseInvoiceFormSet, self).__init__(*args,**kwargs) for form in self.forms: form.fields.update({'min_unit_share': forms.IntegerField(validators = [validate_positive,] ) }) form.fields.move_to_end('min_unit_share', last=False) # Note that self.fields is an ordereddict. To move an item to the front of an ordered dict in Python 3.0+ I get Exception Type: ValidationError Exception Value: ['ManagementForm data is missing or has been tampered with'] When I comment out the dynamically added field, the error goes away. So, the post method of the class view calls the init method as expected. But, for some reason it thinks that I am changing the ManagementForm data. The question is how to get around or resolve this issue. Is there a way to pop out the added field before calling super(BaseInvoiceFormSet, self).init(*args,**kwargs) Note that it seems all the modelformset data is passed through using *args. It is sitting at args[0] and I could not pop the additional field using args[0].pop('min_unit_share') Also, to make things simple, in my template, I use: {% for form in formset %} {{ form.as_p }} {% endfor %} Any … -
Select users with common answers to questions
I have four models including the CustomUser table. class Question(models.Model): question = models.CharField(max_length=140) class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers') answer = models.CharField(max_length=70) class Response(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.ForeignKey(Answer, on_delete=models.CASCADE) Each question has multiple answers but each user can only pick one answer to each question. Each user can answer multiple questions. How do I select a list of users with a nested list of their common answers to a reference user with just the ORM? I can think of a hacky solution of retrieving the list of common answers and then a python loop to increment the count for each user but I would like to confine it to the ORM as I need to append this to a parent serializer (UserSerializer -> ResponseSerializer). -
Getting Request method 'GET' not supported - Python
So I've been trying to request an API using the following endpoint: http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687***** Using the following python code: import requests import json resp_1 = requests.get("http://viatorapi.viator.com/service/search/products?destId=684&apiKey=98765687*****") res = resp_1.json() print(res) But I keep getting a Request method 'GET' not supported error even when I try the request directly from the browser. I've been looking at the documentation for a while now and it's says that It's supposed to be a POST request. Here: https://docs.viator.com/partner-api/affiliate/technical/#tag/Product-services/paths/~1search~1products/post Any ideas on why this is happening and how to fix this? -
How to receive a zip file from a HTTP response
Context Summarizing, I have an app that sends some file or JSON to a Django server, the server then process the file and create a new zip file. This zip file have to return to the app. I'm trying to do this with a POST request only, returning the file as a response. I was able to download the file as a response with Postman and I can also see the response I want inside one of the HttpErrorResponse attributes. I also found an answer that was able to do the same, but in Java. Some informations App: made with Ionic v4 | Server: Django 2.24 Front side attempts Main request method: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json', }), requestType: 'application/octet-stream' }; this.http.post("http://127.0.0.1:8000/converter2/", file, httpOptions) .pipe( finalize(() => { loader.dismiss(); }) ) .subscribe(data => { console.log(data['body']); }, error => { console.log(error); console.log(error.error.text) }); Attempts: With the method above I receive this error: Error number 1 -> SyntaxError: Unexpected token P in JSON at position 0 at JSON.parse I'm receiving this error because the http response, by default, is trying to parse the response. I read the documentation of HttpClient, but don't say much about receiving … -
foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile"
This question doesn't answer to my problem. Here are my classes: class Person(BaseModel): user = models.OneToOneField(User, related_name='person', on_delete=models.CASCADE) class UploadedFiles(BaseModel): person = models.ForeignKey(Person, null=True, blank=True, default=None, related_name='uploaded_files', on_delete=models.CASCADE) common_directory = models.CharField(max_length=200, default=None, null=True, blank=True) tarball_file = models.ForeignKey(UploadedFile, null=True, blank=True, related_name='tarball_file', default=None, on_delete=models.CASCADE) class UploadedFile(BaseModel): description = models.CharField(max_length=200, default=None, null=True, blank=True,) original_file = models.CharField(max_length=200, default=None, null=True, blank=True,) uploaded_file = models.FileField(default=None, null=True, blank=True,) When, in my code I do this: UploadedFiles.objects.create(person=self.request.user.person) I get this error: sqlite3.OperationalError: foreign key mismatch - "app_uploadedfiles" referencing "app_uploadedfile" Any idea how to solve this? -
Is it possible to override LoginView in function based views, not as a class?
I understand that in order to override from django.contrib.auth.views.LoginView one has to use a subclass Class(LoginView) in views.py. However, in my views.py I only have views declared with def my_view(request) In old versions of Django I could just do from django.contrib.auth.views import login, logout def login_user(request): result = login(request=request, template_name='Market/pages/login.html') return result What's the modern Django equivalent of this? The documentation has this example, that forces me rewrite the whole username/password logic into my view: from django.contrib.auth import authenticate, login def my_view(request): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to a success page. ... else: # Return an 'invalid login' error message. ... How can I use a view function (not class!) and still have the automatic managing of the submitted request? -
Django - DoesNotExist at /accounts/signup/ - Membership matching query does not exist
I followed a tutorial on how to deploy django2 on pythonanywhere and than I just added the components from my own app. Everything worked fine in development, but after deployment I cant sign in and all media elements are gone. Traceback: Django Version: 2.2.4 Python Version: 3.6.6 Installed Applications: ['todo', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'qsessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'allauth', 'allauth.account', 'allauth.socialaccount', 'courses', 'memberships', 'star_ratings', 'avatar', 'home', 'online_users', 'django.contrib.sites'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'qsessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'online_users.middleware.OnlineNowMiddleware'] File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper 45. return bound_method(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper 76. return view(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 214. return super(SignupView, self).dispatch(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 80. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in dispatch 192. **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/views/generic/base.py" in dispatch 97. return handler(request, *args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in post 103. response = self.form_valid(form) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/views.py" in form_valid 230. self.user = form.save(self.request) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/forms.py" in save 404. adapter.save_user(request, user, self) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/allauth/account/adapter.py" in save_user 243. user.save() File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/contrib/auth/base_user.py" in save 66. super().save(*args, **kwargs) File "/home/AndrewsBRN/.virtualenvs/myenv/lib/python3.6/site-packages/django/db/models/base.py" in … -
Django User Registration View -- Best Practice
I need user registration to only be open to users that I approve and I want to minimize the amount of info that users have to input. My current solution is to create a uuid for each user in the django admin (via a unique model that contains other relevant information). Once I have done that I send the user a 'registration link' in the form of: www.oursite.com/accounts/register?c={companyID}&ac={accessCode} Then I use my view to capture those url query parameters and use them to verify create a new user: company = None access_code = None def register(request): # www.lunica.com/accounts/register?c={companyID}&ac={accessCode} global company global access_code initial = {} if request.GET: initial = request.GET.copy() company = initial['c'] access_code = initial['ac'] if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] if password == password2: if get_user_model().objects.filter(email=email).exists(): messages.error(request, 'Email is already in use') return redirect('register') else: print(company) if Customer.objects.filter(customer_id=company).exists(): company_access_code = Customer.objects.filter( customer_id=company).values_list( 'access_code', flat=True)[0] if uuid.UUID(str(company_access_code)) == uuid.UUID( str(access_code)): try: company_obj = Customer.objects.get(customer_id=company) except Customer.DoesNotExist: company_obj = None if company_obj != None: user = get_user_model().objects.create_user( email=email, password=password, name=name, customer=company_obj ) auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') else: messages.error(request, 'Admin Error (3): Please contact admin.') … -
OperationalError at /admin/news/article/ no such column: news_article.reporter_id
Models.py from django.db import models from django.utils import timezone class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=255, unique=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Reporter(models.Model): full_name = models.CharField(max_length=70, db_index=True) def __str__(self): return self.full_name class Article(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) category = models.ForeignKey(Category, related_name='article', on_delete=models.CASCADE) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) headline = models.CharField(max_length=200) slug = models.SlugField(max_length=200, db_index=True) image = models.ImageField(upload_to='article/%Y/%m/%d', blank=True) body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def __str__(self): return self.headline I am getting this error while running this code. django.db.utils.IntegrityError: The row in table 'news_article' with primary key '1' has an invalid foreign key: news_article.reporter_id contains a value 'reporter_id' that does not have a corresponding value in auth_user.id. admin.py from django.contrib import admin from .models import Category, Article, Reporter # Register your models here. @admin.register(Category) class CategoryAdmin(admin.ModelAdmin): list_display = ['name', 'slug'] prepopulated_fields = {'slug': ('name',)} @admin.register(Reporter) class ReporterAdmin(admin.ModelAdmin): list_display = ['full_name'] @admin.register(Article) class ArticleAdmin(admin.ModelAdmin): list_display = ['headline', 'slug', 'reporter', 'created', 'updated'] list_filter = ['headline', 'created', 'updated'] prepopulated_fields = {'slug': ('headline',)} -
How are the directories of a Django Project tree referred to?
Assume you have a directory where you keep all your Django projects: $HOME/Programming/Django_Projects If you in this directory call django-admin startproject blog you'll end up with the following director tree: $HOME/Programming/Django_Projects/blog $HOME/Programming/Django_Projects/blog/blog What's the first blog and whats blog/blog? -
How to customize template in django-oscar?
i want to customize django-oscar template according to my requirement , when i modified the checkout page, i had been encoutred with this error : TemplateSyntaxError at /checkout/thank-you/ Invalid block tag on line 132: 'oscar_thumbnail', expected 'endwith'. Did you forget to register or load this tag? this my settings.py : TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), OSCAR_MAIN_TEMPLATE_DIR ] , # 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.contrib.messages.context_processors.messages', 'oscar.apps.search.context_processors.search_form', 'oscar.apps.promotions.context_processors.promotions', 'oscar.apps.checkout.context_processors.checkout', 'oscar.apps.customer.notifications.context_processors.notifications', 'oscar.core.context_processors.metadata', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], }, }, ] how i can register the templatetag into my custom template in django-oscar?