Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model not saving for some reason, may have to do with concurrency
I am using django-channels (which uses websocket). The function below is run every time a user joins a pregame room. the intended behavior is: the person who created the room is saved as game.creator (no problem with this), and the person who enters after is saved as game.opponent. Much of the time, game.opponent is not saved. Does anyone know why? Thanks in advance @channel_session_user_from_http def ws_connect_pregame(message): message.reply_channel.send({"accept": True}) split_message = message['path'].strip('/').split('/') print(split_message) label = split_message[1] gamelabel = split_message[1] gamepk = gamelabel.split('-')[1] game = Game.objects.get(pk=gamepk) user = message.user if not game.creator: game.creator = user if game.creator and game.creator != user: game.opponent = user game.is_full = True game.save() Group('game-' + gamelabel).add(message.reply_channel) message.channel_session['gamelabel'] = gamelabel -
How to find all the points within a certain radius using google maps api
I have a list of locations in my database stored as lng and lat. The django views is returning the longitude and latitude and latitude of the user location.I would like to return all the locations in the database within 10km of a users location. What would be the best way to do this? def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude return render(request,'main/feed.html') -
PostgreSQL tables appear empty in Django
I restored PostgreSQL on pythonanywhere from sql-formatted pg-dump made on my macbook. My tables appear healthy in PostgreSQL, but they appear empty in Django. I suspect I have two schemas or two databases, and the one Django is looking at is empty. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb2', 'USER': 'super', 'PASSWORD': 'bigsecretR4', 'HOST': 'magula6-1249.postgres.pythonanywhere-services.com', 'PORT': '11249', 'OPTIONS': { 'connect_timeout': 60, } } } postgres=# select count(*) from public.cw_city5; count ------- 615 >>> from cw.models import * >>> qs=City5.objects.all() >>> len(qs) 0 -
CORS problem with Django, mising 'Access-Control-Allow-Headers'
I'm having a problem with CORS and Django where, when I try to POST a JSON from my app, I get no response but got an error: Cross-origin request blocked: Same Origin Policy prevents reading of remote resource at http://localhost:8000/converter2/. (Reason: 'access-control-allow-headers' symbol missing in 'Access-Control-Allow-Headers' CORS header during CORS pre-connection). Also, when I try to connect my Django server logs this: "OPTIONS /converter2/ HTTP/1.1" 200 0. Okay, I'm not receiving 'Access-Control-Allow-Headers' from the server. From all I have read this needs to be solved in server side. So I tried to install django-cors-headers and configure it like the following: # settings.py INSTALLED_APPS = [ ... 'corsheaders' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True Sadly nothing changed. So I tried change the CORS_ORIGIN_ALLOW_ALL to False and add my app origin to CORS_ORIGIN_WHITELIST, just like this: CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000' ] Again, nothing changed. I tried now to force the headers with the server response, like suggested in this answer: ... response = HttpResponse(status=201) response["Access-Control-Allow-Origin"] = "*" response["Access-Control-Allow-Headers"] = "X-Requested-With, Content-Type" return response Still nothing, I don't know what else I can try. I would appreciate new suggestions, thank you. Ionic v4, port 8100 Django v2.2.4, port 8000 … -
Is there a way to make a Google Place Photos API request without exposing the API Key?
I'm making a web-app where I need to make a request to the Google Places API, this is all good but I also need to make a request to the Places Photo API to display the images of the stuff I find using the places API. To do this, you need to make a request like this: https://maps.googleapis.com/maps/api/place/photo?parameters Where one of mandatory parameters is your API Key. I'm using Django and I'm passing a dictionary that has all the info I need to display. However, in the frontend you can see the API Key in the URL of the image. Is there any way I can avoid that? Thank you so much! -
Retrieving Data Faster Using Django from a Large Database
I have a large database table of more than a million records and django is taking really long time to retrieve the data. When I had less records the data was retrieved fast. I am using the get() method to retrieve the data from the database. I did try the filter() method but when I did that then it gave me entire table rather than filtering on the given condition. Currently I retrieve the data using the code shown below: context['variables'] = variable.objects.get(id=self.kwargs['pk']) I know why it is slow, because its trying to go through all the records and get the records whose id matched. But I was wondering if there was a way I could restrict the search to last 100 records or if there is something I am not doing correctly with the filter() function. Any help would be appretiated. -
Django Dev Server Processing The Same Ajax Request Inconsistently
I'm submitting a POST using ajax clientside. It works fine whenever all the requests are valid. However, when I send a POST request to an invalid URL, and then follow it up with another POST request, regardless of whether it's valid, Django processes the request in a completely different manner. Before changing some code it was actually causing the server to crash. Heres what happens in the Django server stdout when I send two invalid requests in a row: Not Found: /profile/add_favorite [01/Aug/2019 15:42:25] "POST /profile/add_favorite HTTP/1.1" 404 4132 Not Found: /profile/add_favorite [01/Aug/2019 15:42:30] "title=Video+TitlePOST /profile/add_favorite HTTP/1.1" 404 4178 The second request looks ill-formatted, and it's of a different format than the previous request. The request was sent using basic Ajax: var conf = { type: 'POST', url: url, data: {title: "Video Title"}, headers: {'X-CSRFToken': csrftoken}, } $.ajax(conf) And in the dev tools I checked that the requests were the same: That's just the headers but the data is also the same. Anyways, the exact same code was used for both request. This only happens when I send a request to an invalid URL and then send another request after it, and if I reload the page after sending an … -
How to fix duplicate key value violates unique constraint?
I have customized my user model.I have added many other fields in the user model.When I try to add a user by clicking the button "Add User" on the admin panel of Django .The following error occurs. IntegrityError at /admin/accounts/user/add/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. I am using django2.2 and currently I am learning complex things in django.I have customized my user model .When I try to add a user by clicking this "Add user" in the admin panel of django this error occurs. IntegrityError at /admin/accounts/user/add/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounts/user/add/ Django Version: 2.2 Exception Type: IntegrityError Exception Value: duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Exception Location: C:\Program Files\Anaconda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py in _execute, line 84 Python Executable: C:\Program Files\Anaconda\envs\DjangoEnv\python.exe Python Version: 3.7.3 Python Path: ['E:\\Project\\ProductHuntSite', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\python37.zip', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\DLLs', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\lib', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv', 'C:\\Users\\khana\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Program Files\\Anaconda\\envs\\DjangoEnv\\lib\\site-packages'] Server time: Thu, 1 Aug 2019 22:11:22 +0600 This is my code. class UserManager(BaseUserManager): def create_user(self, username, email, firstname, lastname, profile_photo,mobile_phone_number, password=None, is_staff=False, is_active=True, is_admin=False, is_moderator=False): if not email: raise ValueError("User must have an Email") if not username: raise … -
How to import utils into Django Templates
I'm trying to import a module into my app's settings.py, but am facing the following error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'templatetags.common_utils': No module named 'templatetags'. My file structure looks like this: app |- assets |- templatetags |-__init__.py |-utils.py |- settings.py And in my settings.py, my TEMPLATES array looks like this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], 'libraries': { 'common_utils': 'templatetags.common_utils', }, }, }, ] I don't see why Django is failing to find templatetags in 'libraries': { 'common_utils': 'templatetags.common_utils', }, Any help would be much appreciated ! -
Saving a model in a separate thread
In my simple webapp I have a model called Document. When the document is created it is empty. The user can then request to generate it, which means that its content is filled with data. Since this generating step can take some time, it is an asynchronous request: the server starts a thread to generate the document, the user obtains a quick response saying that the generation process started, and after some time the generation is over and the database is updated. This is the code that describes the model: import time from threading import Thread from django.db import models STATE_EMPTY = 0 STATE_GENERATING = 1 STATE_READY = 2 class Document(models.Model): text = models.TextField(blank=True, null=True) state = models.IntegerField(default=STATE_EMPTY, choices=( (STATE_EMPTY, 'empty'), (STATE_GENERATING, 'generating'), (STATE_READY, 'ready'), )) def generate(self): def generator(): time.sleep(5) self.state = STATUS_READY self.text = 'This is the content of the document' self.state = STATE_GENERATING self.save() t = Thread(target=generator, name='GeneratorThread') t.start() As you can see, the generate function changes the state, saves the document and spawns a thread. The thread works for a while (well,... sleeps for a while), then changes and state and the content. This is the corresponding test: def test_document_can_be_generated_asynchronously(self): doc = Document() doc.save() self.assertEqual(STATE_EMPTY, doc.state) … -
'Post' object has no attribute 'comments'?
I'm a creating a basic blog webapp using django. The app starts without an error but when I click on drafts an error come up with AttributeError at /drafts 'Post' object has no attribute 'comments' I've tried by putting comments = models.Manager() but then another error comes up saying Manager isn't accessible via post instances my models.py class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.PROTECT) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True,null=True) # objects = models.Manager() # comments = models.Manager() def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse('blogapp:post_detail',kwargs={'pk':self.pk}) def __str__(self): return self.title my drafts view look something like class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'blogapp/post_list.html' model = Post def get_queryset(self): return Post.objects.filter(published_date__isnull=True).order_by('create_date') I'm using 'comments' variable in another html and views file. And the same error arise with 'objects' while executing the line Post.objects.filter(published_date__isnull=True).order_by('create_date') in my views.py file -
Skipping over value when inserting data in Django ORM to avoid duplicate error
My table has a composite key using "unique together" like so class ComponentMap(models.Model): key = models.TextField() component = models.TextField() class Meta: unique_together = [['key', 'component']] db_table = 'component_map' as you can see this is connected to my postgres table "component_map" Now this Table is to help figure out if a key has multiple components tied to it. Since there are thousands of different keys, Whenever someone searches for a key, it will grab all the data from a seperate API and then store it into my database to ensure the data will be there. The problem I am having is sometimes whenever someone searches for a specific key that is already in the database to see its components it will give an error duplicate key value violates unique constraint. Usually in Django models it will just update the row if there is a duplicate key, but the unique together seems to break that functionality. What i have tried is this: def insert_data(self, data): values = list((key, name, component_list ) for item in data['issues']) for bug in values: for x in bug[0]: if ComponentMap.objects.filter(key = x): continue for x in bug[2]: c = ComponentMap(key=bug[0], component=x ) c.save() So I thought i … -
Overriding LogoutView.get
I'm trying to override LogoutView.get, to delete an extra cookie. This is my approach: class SignOutView(LogoutView): def get(self, request, *args, **kwargs): """Override get() to delete extra cookie that was set on login.""" res = super().get(request, *args, **kwargs) res.delete_cookie(settings.SESSION_API_KEY_COOKIE_NAME) return res This does not work, the code doesn't seem to be called at all. I don't understand why, when I override a different method, e.g. dispatch, it works as expected. According to http://ccbv.co.uk/ and my understanding of how class based views handle requests, I think I should be able to override LogoutView.get. I'm using Django 1.11.18, but I don't think that matters here. Is there anything obvious that I'm missing? Thanks a lot in advance! -
How to do Django's form client side validation using JavaScript when server side validation already done
I have done Django's form validation at the server-side. Is there any need for client-side validation? If I want to do client-side validation using JavaScript, without writing duplicate validation code at the client-side, can I get Django's server-side validation code at the client-side using JavaScript? So, I can avoid server round-trips and reload time. -
Django “./manage.py bower install
I'm following the instructions from the A calendaring app for Django. setup readme here. I've installed django-bower (v5.1.0) via $ pip install -r requirements.txt (django-bower==5.1.0 is in my requirements.txt). Now I'm trying to run $ ./manage.py bower install but i the commande give me some error he didne found the manage.py the project is : https://github.com/llazzaro/django-scheduler and the error is : ./manage.py : Le terme «./manage.py» n'est pas reconnu comme nom d'applet de commande, fonction, fichier de script ou programme exécutable. Vérifiez l'orthographe du nom, ou si un chemin d'accès existe, vérifiez que le chemin d'accès est correct et réessayez. Au caractère Ligne:1 : 1 + ./manage.py bower geler + ~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (./manage.py:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
Efficient way of joining two query sets without foreign key
I know django doesn't allow joining without a foreign key relation and I can't specify a foreign key because there are entries in one table that are not in the other (populated using pyspark). I need an efficient way to query the following: Let's say I have the following tables: Company | Product | Total # Users | Total # Unique Users and Company | Product | # Licenses | # Estimated Users I would like to join such that I can display a table like this on the frontend Company View Product|Total # Users|Total # Unique Users|#Licenses|# Estimated Users| P1 | Num | Num | Num | Num | P2 | Num | Num | Num | Num | Currently loop through each product and perform a query (way too slow and inefficient) to populate a dictionary of lists Way too inefficient -
DRF: Serializing data from external network request
I'm using Django Rest Framework and making external network request which data isn't needed in models but pure serializers. I make an external request to get some data from a server which returns JSON. Here is a quick snipped of it. { "request": [ { "packages": { "gold": [ { "name": "Gold Package 1", "value": "Gold1" }, { "name": "Gold Package 2", "value": "Gold2" } ], "bronze": [ { "name": "Bronze package 1", "value": "Bronze1" }, { "name": "Bronze Package 2", "value": "Bronze2" } ] } ] } After getting this request, I want to return data within this format. How can this be achieved? "response": [{ "details": { "legacy_packages": [{ "name": "Gold Package 1", }, { "name": "Gold Package 2", } ] } }, -
How to connect one django model to many other models?
I'm trying to develop a property management system. I've created the bedroom and bathroom models. In each bedroom and bathroom I need to add lighting, climatization and entertainment models. I've created those models but I'm not sure if I should create another model like "Lighting_Bedroom" and use the ForeignKeys pointing to both models, or if there's another way to do this. // Bedroom Model class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE) // Bathroom Model class Bathroom(models.Model): sink = models.CharField(db_column='Sink', choices=SINK_BATHROOM_CHOICES, max_length=50) shower = models.CharField(db_column='Shower', choices=SHOWER_BATHROOM_CHOICES, max_length=50) tower_rail = models.CharField(db_column='Tower_Rail', choices=TOWER_RAIL_BATHROOM_CHOICES, max_length=50) image = models.ImageField(null=True) toilet = models.BooleanField(default=False) bidet = models.BooleanField(default=False) bath = models.BooleanField(default=False) extractor_fan = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE) // Properties class Lighting(models.Model): type = models.CharField(db_column='Type', choices=LIGHTING_TYPE_CHOICES, max_length=30) bulb_type = models.CharField(db_column='Bulb_Type', max_length=30) class Climatization(models.Model): type = models.CharField(db_column='Type', choices=CLIMATIZATION_TYPE_CHOICES, max_length=30) use = models.CharField(db_column='Use', choices=CLIMATIZATION_USE_CHOICES, max_length=30) brand = models.CharField(db_column='Brand', max_length=30) model = models.CharField(db_column='Model', max_length=50) remote_control = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. So far I didn't … -
Django: Product matching query does not exist
I have a django-shop project. I add 'add to cart' function and it works. But when I try to get quantity added to cart I get an error 'Product matching query does not exist'. Here is the view that works. def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.POST.get('product_slug') product = Product.objects.get(slug=product_slug) new_item, _ = CartItem.objects.get_or_create(product=product, item_cost=product.price, all_items_cost=product.price) if new_item not in cart.items.all(): cart.items.add(new_item) cart.save() new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count() }) And this view after upgrading and it's not working def add_to_cart_view(request): cart = getting_or_creating_cart(request) product_slug = request.POST.get('product_slug') product = Product.objects.get(slug=product_slug) if request.method == "POST": form = CartAddProductForm(request.POST or None) if form.is_valid(): quantity = form.cleaned_data['quantity'] new_item = CartItem.objects.create(product=product, item_cost=product.price, all_items_cost=product.price, quantity=quantity) if new_item not in cart.items.all(): cart.items.add(new_item) cart.save() print("It's done!") else: print('Not valid') else: print('Not POST') new_cart_total = 0.00 for item in cart.items.all(): new_cart_total += float(item.all_items_cost) cart.cart_total_cost = new_cart_total cart.save() return JsonResponse({ 'cart_total': cart.items.count(), }) Here is the traceback Environment: Request Method: POST Request URL: http://localhost:8000/add_to_cart/ Traceback: File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\tankr\Django_projects\django_shop\eComEnv\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view … -
I want to upload a pdf format file into xampp mysql database table using django
I want to upload a pdf file along with other details of a person using django, Xampp Mysql. For example, along with person's name, address, phone number, I want to upload a pdf file which contains some content related to the person. I've used the below code in modules.py to store person's name, address and contact number. Now, after contact number, I also want to upload a pdf file to the same table using django, mysql. modules.py class person_upload(models.Model): name=models.CharField(max_length=100) address=models.CharField(max_length=100) phone=models.CharField(max_length=100) views.py def w_upload(request): name=request.POST['pname'] address=request.POST['paddress'] phone=request.POST['pphone'] insert=person_upload(name=name, address=address, phone=phone) insert.save() -
Django Object Names , can't compare values
the problem about 2 things ; First of all in admin panel and webpage foreign keys are shown as object(1) ,Yes I know the solution of this we use str stuff but when I try to compare id of them it takes the value of str function result let me show in code; Im checking logged in user's connected company id that equals to only students who are connected with same company model.py - Student class Student(models.Model): id = models.AutoField(primary_key=True, verbose_name='StudentID') parentid = models.ForeignKey(Parent, on_delete=models.CASCADE, verbose_name='ParentID') companyid = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='CompanyID') classid = models.ForeignKey(Classes, on_delete=models.CASCADE, verbose_name='ClassID') gender = models.CharField(max_length=1, default='N', verbose_name='Gender') name = models.CharField(max_length=30, verbose_name='Name') surname = models.CharField(max_length=30, verbose_name='Surname') dob = models.DateTimeField(verbose_name='Doğum Yılı') bloodtype = models.ForeignKey(BloodType, on_delete=models.CASCADE, verbose_name='Blood Type') status = models.BooleanField(verbose_name='State') list_display = ('id', 'parentid', 'companyid', 'classid', 'gender', 'name', 'surname', 'dob', 'bloodtype', 'status') def __str__(self): return "%s %s - %s" % (self.name, self.surname, self.gender) model.py - Company class Company(models.Model): id = models.AutoField(primary_key=True, verbose_name='CompanyID') name = models.CharField( max_length=100, verbose_name='Company Name') contactname = models.CharField(max_length=30) contactsurname = models.CharField( max_length=30) address = models.CharField(max_length=200) city = models.CharField(max_length=20) phone = models.CharField(max_length=12) weburl = models.URLField(max_length=80) email = models.CharField(max_length=80) studentcapacity = models.BigIntegerField(verbose_name='Student Capacity') classcapacity = models.BigIntegerField(verbose_name='Class Capacity') notes = models.TextField(max_length=200) status = models.BooleanField(verbose_name='State') list_display = ('id', 'name', … -
How can I do a hierarchical validation in Django?
I'm writing a Django app, where users can upload CSV files. Therefore I've created an upload model with three validators: One that checks the file extension (FileExtensionValidator), one for the MIME type validation (ValidateFileType), and a third one for parsing the CSV file and checking for data types, right number of columns and so on (ValidateCsv). It'd be reasonable to check the upload only with the next validator if the preceding validation didn't raise a ValidationError. For instance, the user could upload a .py file. This would raise an error in all three validators, but I want to avoid, that Django checks the MIME type or even tries to treat and parse a .py file as a CSV file, although the file extension wasn't correct right from the beginning. So here is my model for the user's upload: models.py from django.db import models from .utils import unique_file_path from django.core.validators import FileExtensionValidator from .validators import ValidateFileType, ValidateCsv class Upload(models.Model): date_uploaded = models.DateTimeField(auto_now_add=True) file = models.FileField(upload_to=unique_file_path, validators=[FileExtensionValidator(['csv']), ValidateFileType, ValidateCsv], max_length=255) With this validators list all three validations are always performed and I can see all the error messages in upload_form.errors. For example: File extension 'py' is not allowed. Allowed extensions are: 'csv'. … -
Beginner Django 2.2 tutorial pt.2 Timezone, datetime, pub_date
From the Official Django 2.2 Tutorial pt2 running manage.py makemigrations polls I don't see the expected "- Add field question to choice" after - Create model Choice and - Create model Question It Could be be something that depends from the settings of my enviroment or system, pycharm... etc.) From that "stupid" point * everything goes wrong. I'm trying and trying since two days with just copy and paste from the original tutorial. Always the SAME in the same point: few tutorial lines after I face problems with the function was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) Pycharm tells me: "pub_date: Expected type "timedelta", got "dateTimeField" instead this is my polls/models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Off course I don't see nothing related to "Add field question to choice" not even after passing the command "python manage.py sqlmigrate polls 0001". This is my terminal output, instead: BEGIN; -- -- Create model Question -- CREATE TABLE "polls_question" ("id" integer … -
How to trigger an events by django when html buttons are cliked
here is the html file form <form action ="fetch" method="post"> <input type="text" name="t1"> <input type="text" name="t2"> <input type="submit" name="b1"> <input type="cancel" name="b2"> </form> now when we click on submit button its properly calls the fetch function but when i click on cancel button same fetch function is called so i don't want that to happen i want to trigger different event/function when user click's on cancel button here is the html file form <form action ="fetch" method="post"> <input type="text" name="t1"> <input type="text" name="t2"> <input type="submit" name="b1"> <input type="cancel" name="b2"> </form> my views.py def fetch(request): a = request.GET.get("t1") b = request.GET.get("t2") return render(request,'student.html') -
Django is not sending email after rest-auth registration
After I change user model to using email instead of username, email is not sending when I access rest-auth.registration.views.RegisterView. What should I do to make working? My email setup is: EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend" It's correct configuration, sending email on rest_auth.views.PasswordResetView works fine. My code: users/urls.py: app_name = "users" urlpatterns = [ path("register/", include("rest_auth.registration.urls")), ... ] config/urls.py: from allauth.account.views import AccountInactiveView urlpatterns = [ ... path("api/v1/users/", include("myproject.users.urls")), # this url is used to generate email content # https://github.com/Tivix/django-rest-auth/blob/master/demo/demo/urls.py path("password-reset/<uidb64>/<token>/", TemplateView.as_view(), name="password_reset_confirm") # for some reason required for rest-auth register view working path("account-inactive/", AccountInactiveView.as_view(), name="account_inactive"), ] config/settings.py ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_USER_MODEL_USERNAME_FIELD = None ACCOUNT_USERNAME_REQUIRED = False After accessing register view, there's no error. User object is created and response (code 201) is: { "detail": "Verification e-mail sent." } However there's no email sent. Thanks for help!