Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Shopify get access token in Python
I should be able to get an access token for Shopify in Django with access_token = requests.post('http://<myshop>.myshopify.com/admin/storefront_access_tokens.json?') but it doesn't work. Any ideas why? -
What is the best way to abstract the API calls in Django?
When I'm calling API from the client. It is visible in the network tab of google chrome. What is the best way to hide that if I'm writing my APIs in django? -
Django filter and display in template if object exists
models.py: class Level(models.Model): number = models.IntegerField() badge = models.ImageField() locked_badge = models.ImageField() timestamp= models.DateTimeField(auto_now_add=True,auto_now=False,blank=True, null=True) unlock = models.CharField(max_length=10,default="A") def __str__(self): return str(self.number) def get_absolute_url(self): return reverse('student:level-detail', kwargs={'pk': self.pk}) class ToDo(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) name = models.CharField(max_length=150) description = models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False,blank=True, null=True) def __str__(self): return self.name class PostManager(models.Manager): def active(self, *args, **kwargs): # Post.objects.all() = super(PostManager, self).all() return super(PostManager, self).filter(draft=False).filter(publish__lte=timezone.now()) class Task(models.Model): level = models.ForeignKey(Level, on_delete=models.CASCADE) todo = models.ForeignKey(ToDo, on_delete=models.CASCADE) student = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=150) content = models.TextField() timestamp = models.TimeField(auto_now=True) datestamp = models.DateField( auto_now=True) like = models.ManyToManyField(User,related_name='user_likes',blank=True) is_verified=models.BooleanField(default=False,blank=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('student:dashboard') objects = PostManager() @property def comments(self): instance = self qs = Comment.objects.filter_by_instance(instance) return qs @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type template: {% for obj in task.todo_set.all %} <div class="card"> <div class="card-header" id="headingOne"> <h5 class="mb-0"> <button style="width: 100%;" class="btn" data- toggle="collapse" data-target="#{{ obj.id }}" aria-expanded="true"> #Only display based on condition <span class="mytaskbutton"><i class="fas fa-check"></i> </span></i> &nbsp; {{ obj.name }} </button> </h5> </div> <div id="{{ obj.id }}" class="collapse" aria- labelledby="headingOne" data-parent="#accordion"> <div class="card-body"> {{ obj.description }} <div> <a data-click="swal-taskcompleted" href="{% url 'student:task- form' task.id obj.id %}" style="width: 100%;" type="button" class="btn btn-primary">Proceed</a> </div> </div> </div> </div> {% … -
How to interact with cmd through a file?
My commands.bat file contains: py manage.py makemigrations ParameterManager py manage.py migrate py manage.py createsuperuser These commands are executed. Now cmd asks for a username, email and password. How do I answer to these questions from the file, without the need for user interaction? -
Parameter shown as "0:" in ajax request
var frm = $('#updateStickyForm'); frm.submit(function (e) { var id = "{{note.id}}" e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize() + '&' + $.param(id), success: function (data) { console.log('Submission was successful.'); $('#test').show(); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, }); }); When I look at the network logs in Chrome the parameter is shown as "0:". I'm able to access the parameter just fine with Django and do what I want to do with it, I just want to know how I can change it from "0" to something of my choosing. -
Django problem with having slug in my url while using a class templateview in views
First i was using a detailslist which was working fine, but i wanted to add a widget to show similar post (post in same category) so i had to change my def to a class to put a def get_context_data(self, pk), but now it always say get_context_data() got an unexpected keyword argument 'slug' here is my url url(r'^(?P<slug>[\w-]+)$', views.postdetails.as_view(), name="postdetails"), my view class postdetails(TemplateView): model = Post template_name = 'blog/postdetails.html' def get_context_data(self, pk): context = super(postdetail, self).get_context_data(**kwargs) cat_id = self.kwargs.get('pk', None) category = get_object_or_404(Category, id=cat_id) getcat = category.post_set.all().order_by("-date") resultcat = random.sample(getcat,4) context['similarpost'] = resultcat return context and my model if needed class Post(models.Model): title = models.CharField(max_length = 140, unique=True) slug = models.SlugField(max_length=40, blank=True, unique=True) image = models.ImageField(upload_to="media", blank=True) body = RichTextField(config_name='default') date = models.DateField() category = models.ManyToManyField(Category) def __str__(self): return self.title i guess the django detailview was doing something to come up with the right slug, but i dont know what it was, how can I make this work ? thanks a lot -
How schedule a job (Django, Python)
I would like to create a job that rolls to all 10 munites. I find a good example here. The problem is that the program is freezing during the waiting time and my other urls are blocked. after me it's because of while True: Is there a way to do it without going around this problem? voici le code: import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) while True: schedule.run_pending() time.sleep(1) -
django.db.utils.ProgrammingError: can't adapt type 'property'
I have a model that includes a GenericForeignKey. class POSRecord(models.Model): id = SmallUUIDField(default=uuid_default(), primary_key=True, db_index=True, editable=False, verbose_name='ID') # FK to a POS integration (e.g., SquareCredentials) pos_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_integration', on_delete=models.CASCADE) pos_id = models.CharField(max_length=100) pos = GenericForeignKey('pos_content_type', 'pos_id') # FK to anything in our system (e.g., Item, ModifierList, Location) object_content_type = models.ForeignKey('contenttypes.ContentType', related_name='pos_record_object', on_delete=models.CASCADE) object_id = models.CharField(max_length=100) object = GenericForeignKey('object_content_type', 'object_id') # Raw JSON data from the POS api data = JSONField() objects = POSRecordManager() the model work fine it just that when create a POSRecord object and try to access a a value from that object i get a django.db.utils.ProgrammingError: can't adapt type 'property' this is my helper function that helps create POSRecord object def create_record(self, pos, object, data): return self.create( pos_content_type=ContentType.objects.get_for_model(pos), pos_id=pos.pk, object_content_type=ContentType.objects.get_for_model(object), object_id=object.pk, data=data ) this is where i call the helper function to create POSRecord object. this works. record = POSRecord.objects.create_record( pos=self.credentials, object=ModifierList, data=square_modifier.to_dict() ) modifier = record.object but when i call the record.object and assign that to variable i get django.db.utils.ProgrammingError: can't adapt type 'property' but if i call record.pos it doesn't throw an error. not sure why. -
Django: Allow creation of model only within time period
In my web application I have the model Event and the model Registration (for an event). Let's say the Event takes place on 31 January 2019 at 13:00. Now, I have to make sure that people can only register e.g. until the registration deadline that is defined in the Event model. I'm using CBVs in Django and I'd like to ask WHERE I should put the check in the code so that people can only CREATE new registrations until the registration deadline. In my template I've this check already and the form is only displayed when it's before the deadline. However, I also have to make sure that people who know the form cannot POST to the specified site. Is there a default way in Django to solve this problem? In which method should I check that? -
'invalid literal for int() with base 10:' error when retrieving record with Django REST
Basically I am trying to retrieve information on a specific VIN for car, I do so with the URL pattern: ValueError at /api/v1/purchases/1D7RV1CT0AS168723/ with the VIN there as the pk. It was working fine before, not sure what changed views.py -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from rest_framework import viewsets from django.shortcuts import get_object_or_404, get_list_or_404 from .models import GetPurchases, CarFax from .serializers import PurchasesSerializer from .serializers import CarFaxSerializer from rest_framework.response import Response # Create your views here. class getPurchases(viewsets.ModelViewSet): ''' The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy(). ''' queryset = GetPurchases.objects.all() serializer_class = PurchasesSerializer def list(self, request): # accessed at url: ^api/v1/purchases/$ queryset = GetPurchases.objects.all() serializer = PurchasesSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): # accessed at url: ^api/v1/purchases/{pk}/$ queryset = GetPurchases.objects.all() # https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/#get-object-or-404 record = get_object_or_404(queryset, pk=pk) serializer = PurchasesSerializer(record) return Response(serializer.data) -
Django insert into DB works, but psql cli doesn't seem to show it
I'm writing tests for a Django web app. And in my setupTestData class method i'm manually creating some user like below cls.user = get_user_model().objects.create_user(cls.username, email=cls.email, password=cls.password, first_name=cls.first_name, last_name=cls.last_name) The call above goes without failing. But the record doesnt seem to exist at all in DB. How I'm able to confirm this is in the real test methods, the API's fail because the User doesn't seem to exist in DB. I however crossed checked this. By using import pdb # I use this after the .create_user() line to stop execution # and use psql cli to inspect the test DB but i can't see the inserted row pdb.set_trace() Inside pdb, i use the following to debug if Django ORM has saved the record. (Pdb) display cls.user.pk display cls.user.pk: 1 Meaning the insertion as been given an id 1. But running select count(*) from Authorization_users in psql gives 0 rows. I need help in debugging this further. Thanks -
Fetching reverse foreign key of reverse foreign key in django while still taking advantage of prefetch_related
I have the following models (these are simplified significantly): class Job(models.Model): name = models.CharField(max_length=255) def get_date_details(self): pass #return a list of all jobdate --> details class JobDate(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE, related_name='dates') date = models.DateField() # ... and a bunch of other fields class JobDateDetail(models.Model): job_date = models.ForeignKey(JobDate, on_delete=models.CASCADE, related_name='details') detail = models.CharField(max_length=255) # ... and a bunch of other fields And regularly need to process the JobDateDetails for all Jobs in the database (several thousand). I know I can prefetch all of the data with a query like: q = Job.objects.all().prefetch_related('dates', 'dates__details') However I am not sure how to best take advantage of the prefetched data in Job.get_date_details(). One option would be to do something like: class Job(models.Model): def get_date_details(self): details = [] for job_date in self.dates.all(): details += [detail for detail in job_date.details.all()] return details However, I suspect there may be a way to query all of those JobDateDetail objects directly. One thing to note- as said before, I realize I can go the other direction to grab all details in one pass, however in this case I am using Django Rest Framework, and need to assemble the details as a field in the Job serializer, requiring me … -
Creating a quiz with Django
I'm trying to build a quiz using Django but I've got some doubts. I've got my piece of code in which the text of the questions and the answers are displayed. I'm also able to read which answers did the user select for that question. The problem now is that I want this to be repeated like 10 times, I mean, I want the user to answer 10 different questions. I was wondering which is the best method to do so, I've thought about saving in the database the user which is doing the quiz and the questions he/she has already answered but I don't like much that method. I've been thinking about using session cookies but I'm not familiar to them. -
Using Django OAuth-Toolkit for Messenger Platform authentication
I have a Django application that I want to communicate with from the Messenger Platform (messenger chatbot). In order to link my backend accounts to the chatbot, I added an OAuth Authentication Server following this tutorial: Django OAuth-Toolkit - Tutorials - Part 1 I'm using the Django OAuth-Toolkit with out-of-the-box settings. So far so good. Unfortunately, I realized that the messenger authentication flow is not following the OAuth2 specs very strictly (as also mentioned OT here). In particular, in OAuth2 it is expected that the auth server redirects back to callback_uri/?code=AUTHORIZATION_CODE , however messenger expects an authorization_code parameter instead of the code one. So now I'm wondering what the easiest way would be to change Django OAuth-Toolkit's behavior and use ?code=AUTHORIZATION_CODE or whether I'm doing something completely wrong. Any help is very much appreciated. If someone used Django OAuth-Toolkit or plain Django to connect to the Messenger Platform already, some example code would be super helpful. -
Does Django provide any built-in way to update PostgreSQL autoincrement counters?
I'm migrating a Django site from MySQL to PostgreSQL. The quantity of data isn't huge, so I've taken a very simple approach: I've just used the built-in Django serialize and deserialize routines to create JSON records, and then load them in the new instance, loop over the objects, and save each one to the new database. This works very nicely, with one hiccup: after loading all the records, I run into an IntegrityError when I try to add new data after loading the old records. The Postgres equivalent of a MySQL autoincrement ID field is a serial field, but the internal counter for serial fields isn't incremented when id values are specified explicitly. As a result, Postgres tries to start numbering records at 1 -- already used -- causing a constraint violation. (This is a known issue in Django, marked wontfix.) There are quite a few questions and answers related to this, but none of the answers seem to address the issue directly in the context of Django. This answer gives an example of the query you'd need to run to update the counter, but I try to avoid making explicit queries when possible. I could simply delete the ID … -
Django how to manage long background process?
I Django newbie and struggle with right decision about background process management. I have a task: unregistered user upload a file then I have to parse it and do some stuff which takes 30-50 sec depends on file. Firstly, I thought just call function from view before render. This function can manage data using additional classes and so on. Then it just return a result to a variable and render send it to a template. example: result = file_handle_function(request.FILES['file']) return render(request, 'home/home.html', {'form': form, 'result': 'result'}) Secondly, I have read about celery a little, but I think it fits more for authenticated user. Though I'm going to make auth system later. Which way I should choose? Any suggestions, links, criticism are welcome =) -
Block a slot of time permenantly (break time)
I m using full calendar to book slots for students. I need to introduce a break time for the teachers. Any idea how to do do? Say my slots are of 45 minutes from 9 to 19. And there is two breaks of 20mn each and a lunch hour that needs to be blocked in the calendar. Any idea how to acheive this? -
Magnify django thumbnail on mouse hover in django admin
How to add css hover effect to this django admin function that displays thumbnail in the admin section. To magnify the size of the image def image_tag(self): if self.image: return mark_safe('<img src="%s" style="width: 50px; height:40px;" />' % self.image.url) else: return 'No Image Found' image_tag.short_description = 'Image' -
Django form "soft" validation, send back to user for explicit confirmation of doubtful data
I have an integer field in a form that must be in the range 100 to 1000. However, if a value other than 100, 200, 381 (don't ask), 525 or 1000 is entered, it is quite probable that this is erroneous. What I'd like to do is what I'm calling "soft validation" -- I don't know if there is any standard terminology. The first time, the form would raise errors and then "Confirm?" boolean field(s) would be added, default false. If it comes back again with the confirm field(s) true, then unlikely data will be accepted. I've got some ideas on how to implement it, but I'd rather not re-invent the wheel. Does anybody know whether this has already been done in open-source code in a generalized re-usable way? I don't know what to search for with Google. I can't find anything obvious at https://djangopackages.org/ -
Django python - are class attributes values shared between requests?
Let's say I have the following class in Python: class MyClass(): cls_att = [] Now, in one of the requests I'm doing the following: MyClass.cls_att.append('a') If immediately after this 'append', another request will get the attribute: lst = MyClass.cls_att What they will get in 'lst'? is it empty list or ['a']? -
Track quantity in inventory
I'm trying to list the number of a certain product I have in my Shopify inventory. I use the url: '...admin/inventory_items.json?ids=myid' Where myid is an integer which is the product_id for that product. I've tried everything which has id in it the json response and I must be putting the wrong number in because all I get back is: {'inventory_items': []} My Django code is def inventory(request): url = '...admin/inventory_items.json?ids=myid' inventory = ((requests.get(url)).json()) print(inventory) return render(request, 'Stock/inventory.html', { 'inventory': inventory }) -
how to load csv file data into pandas using request.FILES(django 1.11) without saving file on server
i just want to upload .csv file via form, directly in to pandas dataframe in django without saving physically file on to server. def post(self, request, format=None): try: from io import StringIO, BytesIO import io print("data===",request.FILES['file'].read().decode("utf-8")) # print("file upload FILES data=====",pd.read_csv(request.FILES['file'].read(), sep=',')) #print(request.FILES) print("file upload data df=====11") mm = pd.read_csv( BytesIO(request.FILES['file'].read().decode("utf-8"))) print("dataframe data=====",mm) # import io, csv # urlData = request.FILES['file'] # data = [row for row in (csv.reader(urlData))] # print("file upload data df=====222",data) # mm = pd.read_csv() #excel_file = request.FILES['file'] # movies = pd.read_excel(request.FILES['file']) except Exception as e: print(e) log.debug("Error in CheckThreadStatus api key required "+str(e)) return Response(responsejson('api key required', status=404)) -
How to configure the Database setting Django-MSSQL (windows)?
I'm new to Django and currently trying to connect my project using python 3.6.4 and Django2.1.2 with SQL server, I tried multiple drivers connectors (libraries installed), but without result, the last driver connector I used is pyodbc: Settings,but some errors appeared:enter image description here thanks for helping me to find a solution. -
rotate text in degrees using python
I am not able to rotate text in degress using python.I also not found rotate method in python. In pyfpdf also not found rotate method. Is there any custom function to solve this issue? -
django constance causes transaction error
I use django 1.11 the admin can configure if the passwords should be complex or not, therefore i used constace to enable this configuration. settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': { 'min_length': 8, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, {'NAME': 'timeline_prototype.apps.core.password_validators.NumberValidator', }, # {'NAME': 'timeline_prototype.apps.core.password_validators.UppercaseValidator', }, # {'NAME': 'timeline_prototype.apps.core.password_validators.LowercaseValidator', }, # {'NAME': 'timeline_prototype.apps.core.password_validators.SymbolValidator', } ] CONSTANCE_CONFIG = { 'PASSWORD_LIFETIME': (365*25, _('The time in Days how long a Password is valid'), int), 'PASSWORD_COMPLEXITY': (True, _('When set to true the Password must contain symbols, numbers, and upper/lowercase letters.')), 'SESSION_COOKIE_AGE': (14*24*60, _('The time in minutes how long a session is valid'), int), } password_validation.py: from constance import config class NumberValidator(object): def validate(self, password, user=None): is_complex = bool(config.PASSWORD_COMPLEXITY) if is_complex: if not re.findall('\d', password): raise ValidationError( _("The password must contain at least 1 digit, 0-9."), code='password_no_number', ) def get_help_text(self): if config.PASSWORD_COMPLEXITY: return _( "Your password must contain at least 1 digit, 0-9." ) else: return '' When creating a new user over the admin interface i get the following: current transaction is aborted, commands ignored until end of transaction block The code works when i remove the config.PASSWORD_COMPLEXITY part. Any explanating why this does …