Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store env variables other than inside gunicorn.service for a Django project?
I tried putting all my environment variables for my Django project inside ~/.bash_profile and then use it in gunicorn.service with EnvironmentFile=/home/user/.bas... but with no luck. Eventually I had to put everything in ExecStart with -e in front of every variable, also with SECRET_KEY and everything in plain text. Is it safe, is it possible to access this externally or how else could I do this? -
Python 3 / Django 2, Passing a dictionary value to form field before saving
I'm trying to get my app to use a serial number, entered on a form, to compare to a dictionary and update a product field on a form before saving. Here's the details: Dictionary is two columns, 'Product Code', and 'Product' The first three digits of the Serial number entered on the form will match to the Product Code in the dictionary. Once the user submits the form, I want it to evaluate the serial number's first three digits, compare it to the dictionary keys, then change the 'product' form field to the dict['Product'] before saving the form. Here is my view: def create(request): #Page with input form to submit new records if request.method == 'POST': form = RecordForm(request.POST) if form.is_valid(): sn = request.POST.get('serial') with open('prodlist.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if sn[0:2] in row['Product Code']: form.fields['product'].update = row['Product'] else: pass form.save() return HttpResponseRedirect('/tracker/all/') else: form = RecordForm() return render(request, 'tracker/form2.html', {'form': form}, RequestContext(request)) With this, I'm geting a key error for the 'product' piece. Is there a way to pass a value to a form field after it is submitted? -
json.loads isnt working with AJAX call
I have an AJAX function which sends an array to my Django Backend. This is the AJAX: function send(){ var set_name = $('#class_name').val(); //console.log(ids) //console.log(set_name) var url = window.location.pathname; $.ajax({ method: "POST", url: url, data: { 'set_name': set_name, 'student_ids': JSON.stringify(ids), }, dataType: 'json', success: function (data) { //location.href = data.url;//<--Redirect on success } }); } I am trying to convert the string that is being sent from the AJAX to a list, however json.loads() isnt working. This is the python: student_ids = request.POST.get('student_ids', None) students_ids = json.loads(student_ids) Thanks for any help -
Django: using an annotated aggregate in queryset update()
I've run into an interesting situation in a new app I've added to an existing project. My goal is to (using a Celery task) update many rows at once with a value that includes annotated aggregated values from foreign keyed objects. Here are some example models that I've used in previous questions: class Book(models.model): author = models.CharField() num_pages = models.IntegerField() num_chapters = models.IntegerField() class UserBookRead(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) user_book_stats = models.ForeignKey(UserBookStats) book = models.ForeignKey(Book) complete = models.BooleanField(default=False) pages_read = models.IntegerField() class UserBookStats(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) total_pages_read = models.IntegerField() I'm attempting to: Use the post_save signal from Book instances to update pages_read on related UserBookRead objects when a Book page count is updated. At the end of the signal, launch a background Celery task to roll up the pages_read from each UserBookRead which was updated, and update the total_pages_read on each related UserBookStats (This is where the problem occurs) I'm trying to be as lean as possible as far as number of queries- step 1 is complete and only requires a few queries for my actual use case, which seems acceptable for a signal handler, as long as those queries are optimized properly. Step 2 is more involved, hence the delegation … -
Django Rest Framework, display data from a table referenced with a foreign key
I got stuck a bit with a small problem when doing my school project, the problem is that I have an api with DRF and wanting to show my patient data "main table" shows them without problems but when I want to show other patient data in a different table (this table is this reference with a foreign key to Patient) I have not managed to obtain the patient data from this other table. I can not make my api send me the other patient data from the foreign key referenced to the patient, could you help me? models.py class Paciente(TimeStampedModel): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) udi = models.UUIDField(default=uuid.uuid4, editable=False) first_name = models.CharField('Nombre(s)', max_length=100) last_name = models.CharField('Apellidos', max_length=100) gender = models.CharField('Sexo', max_length=20, choices=GENDER_CHOICES) birth_day = models.DateField('Fecha de nacimiento', blank=True, null=True) phone_number = models.CharField('Número de telefono', max_length=13) civil_status = models.CharField('Estado civil', max_length=20, choices=CIVIL_STATUS_CHOICES) etc..... class Antecedentes(TimeStampedModel): """ Modelo de motivo y antecedentes de la enfermedad presentada en el momento de la consulta """ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) paciente = models.ForeignKey(Paciente, on_delete=models.CASCADE, null=True) motivo = models.TextField('Motivo de la consulta') antecedentes = models.TextField('Antecedentes de la enfermedad actual', blank=True, null=True) serializers.py class antecedenteSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source="user.username") class Meta: model = Antecedentes fields = ('paciente' ,'motivo', … -
django Inheriting from helper class
I wanted to make wallets for BTC and LTC coins in my models. But since most of the code will be same apart from the coin_name and tx_fees. So, I thought of making a helper class like this : Wallet class ( snippet ) class Wallet(models.Model): name = models.CharField(max_length=80, editable=False) trading_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_amt = models.FloatField(default=0, validators=[MinValueValidator(0.0), ]) wallet_address = models.CharField(default='', blank=True, max_length=100) coin_name = '' <-- will it serve the purpose ? tx_fee = 0 <-- and this ? def __init__(self, coin_name, tx_fee): self.coin_name = coin_name self.tx_fee = tx_fee @transaction.atomic def moveToTrading(self, amount): if amount > self.wallet_amt: return "Insufficient balance" else: self.trading_amt += amount self.wallet_amt -= amount return True @transaction.atomic def withdraw(self, amount, withdrawal_wallet_addr): if amount > self.wallet_amt: return "Insufficient balance" else: # First check if withdrawal address entered by user is # correct, using wallet daemon , if not return error if check_wallet(withdrawal_wallet_addr, "btc"): # initiate checkout return initiate_checkout(withdrawal_wallet_addr, self.coin_name, self.tx_fee) else: return "Incorrect Wallet address" def save(self, *args, **kwargs): self.name = gen_random_string('btc_wallet') super(Wallet, self).save(*args, **kwargs) def deposit(self, amount): self.wallet_amt += amount def __unicode__(self): return self.name def __str__(self): return self.name The use of coin_name is only while creating wallet address name like this : _btc_wallet_<64 char … -
jquery popup dosent iterating for Models values in Django
Issue : Jquery Popup doesn't iterate for model values in Django application, only the last value from query set it popup for all button. QuerySet values which are rendering from model to template via views are as below: <QuerySet [<CheckList: Feeds (S/N/L)>, <CheckList: EU/NY feeds>, <CheckList: EPSCPORT Feeds>, <CheckList: 9:00 AM IST time should be compeleted>, <CheckList: PL fees>, <CheckList: LOAD job should be completed>, <CheckList: Check all FD job status>, <CheckList: Cut off job should be completed>, <CheckList: Do the Health checks>, <CheckList: Check the Statement generation>, <CheckList: Check Service now tickets>, <CheckList: Check application status>, <CheckList: Perform the ELT health checks>]> The home.html file looks like: {% include 'header.html' %} {% load static %} {% include 'snippets/external.js' %} {% include 'snippets/nav.html' %} <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <script type="text/javascript" src="http://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.js"></script> <link rel="stylesheet" type="text/css" href="http://rawgit.com/vitmalina/w2ui/master/dist/w2ui.min.css" /> <body> <!-- --> <table class="table"> <tr> <th>Expected Time</th> <th>SLA Time</th> <th>Application</th> <th>Check Discription</th> <th>Check Details</th> <th>Task Handle by</th> <th>Completed time</th> <th>Start Effort</th> <th>Status</th> </tr> </thead> <tbody> {% for i in query_set %} <tr> <td><small class="text-muted d-block">{{ i.expected_time }}</small></td> <td><small class="text-muted d-block">{{ i.sla_time }}</small></td> <td><small class="text-muted d-block">{{ i.app_name }}</small></td> <td><small class="text-muted d-block">{{ i.check_discription }}</small></td> <td class="align-middle"> <button class="w2ui-btn" onclick="popup()"> <img src="{% static "file.png" %}" alt=" width="30" height="30"/></button> … -
Select Option for a field not related to anything?
How would you handle a scenario with a floating inline table that is a dimension in a pre-existing database that doesn't relate to the user in anyway? The goal is to load this table into a select option in a template, then post a save to the database on a submit. So there will be a relationship from the request to Table 1 at a later point in my model, going from the Request model to the Table1 model. The model: class Table1(models.Model): field1 = models.CharField(db_column='Unit_Num', max_length=5, blank=True, null=True) field2 = models.CharField(db_column='Company_Code', max_length=1, blank=True, null=True) class Meta: managed = False db_table = 'Table1' The view i'm not sure about but i think it would be: table1 = Table1.objects.all() args = {'table1':table1} return render(request, 'accounts/profile.html', args) Now to populate the select I tried the following in my template but it just puts a bunch of empty boxes: {% for table in table1 %} <select table1select="Choose a Option..." class="chosen-select" multiple tabindex="4"> <option value="{{table1.select}}"></option> </select> {% endfor %} I'm guessing it's empty because there is no relationship to the User, but i just want to list every row in the database for field1. -
Django Model Form not saving to databased when filled out with AJAX data
I am trying to save data from an ajax call to the database by using a model form. I think the problem is that the form isnt valid, as test is printed when the code runs. This is the Post part of the class based view def post(self, request): set_name = request.POST.get('set_name', None) form = SetCreate(request.POST) if form.is_valid(): instance = form.save(commit = False) instance.name = set_name teacher = Teacher.objects.get(user = request.user) instance.teacher = teacher instance.save() else: print('test') This is the Form: class SetCreate(forms.ModelForm): class Meta: model = Set fields = ('name', 'teacher', 'students') This is the AJAX: function send(){ var set_name = $('#class_name').val(); //console.log(ids) //console.log(set_name) var url = window.location.pathname; ids = JSON.stringify(ids) $.ajax({ method: "POST", url: url, data: { 'set_name': set_name, 'student_ids': ids, }, dataType: 'json', success: function (data) { //location.href = data.url;//<--Redirect on success } }); } Thanks for the help! -
Loggers in django not printing with-out debug mode
I have been working with Django for around 3-6 weeks now and I have been trying to log data on requests to the console and once that works make it go to files once deployed. from django.shortcuts import render, redirect from django.contrib import auth import logging logger = logging.getLogger(__name__) def err_not_found(request): user = check_access(request) if user is None: return redirect("/") logger.info(user) logger.info("Testing this stuff.") return render(request, "404.html", { 'title': "Error", 'user': user }, status=404) That code works perfectly fine, in Debug mode on Django the loggers print but with Debug off, it doesn't. This is my LOGGING section of my Django settings.py file. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, }, 'handlers': { 'console': { 'level': 'NOTSET', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { '': { 'handlers': ['console'], 'level': 'NOTSET', 'propagate': True, }, 'django.request': { 'handlers': ['console'], 'propagate': False, 'level': 'ERROR', }, } } My goal is to be able to do logger.info() or logger.error() with-in views and have it print to the console and then to a file after I configure it when going into a production environment. Django: 2.0.1 Python: 3.6.4 -
How to Debug Django's Javascript?
How do you debug Django's JAvascript using Visual Studio Code, Brackets, or Atom? The documentation for these editors only talks about Node.js on server side. -
boto3 mturk send_bonus error
When I try to send bonus via Boto3 regularly (but not always) the RequestError appears: Exception Type: RequestError Exception Value: An error occurred (RequestError) when calling the SendBonus operation: This user is not authorized to perform the requested operation. Exception Location: /Users/chapkovski/mynewotree/lib/python3.5/site-packages/botocore/client.py in _make_api_call, line 615 the code is the following: response = client.send_bonus( WorkerId=self.WorkerId, BonusAmount=str(form.cleaned_data['bonus_amount']), AssignmentId=self.AssignmentId, Reason=form.cleaned_data['reason'], ) Since it works sometimes, it seems that there is a certain maximum amount that can be sent as a bonus per day. I do it in Sandbox so definitely it is not a problem of lack of funds. Anyone else has encountered the similar issue? -
How to get every objects one at a time Django
Sorry if the question is confusing I'm not an english speaker Here is my def : @register.inclusion_tag('menu/home.html') def show_menu(): buttonname = Button.objects.all() return {'button': buttonname} Here is my home.html : {% for buttons in button %} <li class="nav-item"><a class="nav-link" href=""> <button class="btn" type="submit"><i class="fa fa-bullhorn" aria-hidden="true"></i> {{ button }} </button> </a></li> {% endfor %} The problem is that it display the queryset of all the buttons everytime. How do I display one object one at a time ? Thanks ! -
Caught up in a Type Error: __init__() takes 1 positional argument but 2 were given
I am following this particular tutorial (tutorial link) to get my dynamic formsets working. I encountered this error which I am not sure where is it originated from or how to resolve it. Can someone tell me what could be done to resolve it? Yes, I know that this is a repetitive question here in SO. I have gone through many of those answers, but could not figure it out in my case. View code: class ProfileList(ListView): model = Profile class ProfileFamilyMemberCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] success_url = reverse_lazy('purchase_order') def get_context_data(self, **kwargs): data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs) if self.request.POST: data['familymembers'] = FamilyMemberFormSet(self.request.POST) else: data['familymembers'] = FamilyMemberFormSet() return data def form_valid(self, form): context = self.get_context_data() familymembers = context['familymembers'] with transaction.atomic(): self.object = form.save() if familymembers.is_valid(): familymembers.instance = self.object familymembers.save() return super(ProfileFamilyMemberCreate, self).form_valid(form) -
Django-rest-framework update user from another user that does not work
I need to update a user from another user. But when I do serializer.save () it just does not save to the database. My user model: class User(AbstractBaseUser, PermissionsMixin): class Meta: db_table='empresa_user' email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name = models.CharField(verbose_name='User first name', max_length=30, blank=False) last_name = models.CharField(verbose_name='User last name', max_length=30, blank=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) dt_criacao = models.DateTimeField(null=True, default=timezone.now) perfil = models.CharField(verbose_name='Perfil do usuário', max_length=1, blank=False, null=False, default='B') empresa = models.ForeignKey(Empresa, related_name='empresa', on_delete=models.DO_NOTHING, null=False, blank=False, verbose_name='Empresa') objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ('first_name', 'last_name') def get_full_name(self): return self.first_name +' '+ self.last_name def get_short_name(self): return self.first_name def __str__(self): return self.email My serializer: class UpdateUserPerfilSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = ('perfil', ) def validate_perfil(self, value): if value not in ('A', 'G', 'B', ): raise serializers.ValidationError("Perfil inválido") return value My view: @api_view(['PUT']) @permission_classes((permissions.IsAuthenticated,)) def put_user(request, pk): empresa = get_empresa(request.user) try: user = get_user_model().objects.get(empresa=empresa, pk=pk) except get_user_model().DoesNotExist: raise Http404 serializer = UpdateUserPerfilSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I'm making the call like this: curl -X PUT 'http://localhost:8080/empresa/usuario/15/' -H 'Authorization: JWT MY_TOKEN' -d '{"perfil":"B"}' And that is my response: {"perfil":"A"} -
Django SuccessMessageMixin and jQuery notification function
I need call my notify function when form will be submited CreateView class in my views.py Django class will send message as success_url to the template and i need to catch message and show with jquery function class VisitorCreateView(generic.CreateView): template_name = 'visitor_add.html' form_class = VisitorCreateViewForm success_url = reverse_lazy('visitor:visitor_add') def form_valid(self, form): messages.success(self.request, message='Successfully added') return super(VisitorCreateView, self).form_valid(form) Notify function function notify(from, align, icon, type, animIn, animOut){ $.notify({ icon: icon, title: 'Visitor', message: 'was successfully added', url: '' },{ element: 'body', type: type, allow_dismiss: true, placement: { from: from, align: align }, offset: { x: 20, y: 20 }, spacing: 10, z_index: 1031, delay: 2500, timer: 1000, url_target: '_blank', mouse_over: false, animate: { enter: animIn, exit: animOut }, template: '<div data-notify="container" class="alert alert-dismissible alert-{0} alert--notify" role="alert">' + '<span data-notify="icon"></span> ' + '<span data-notify="title">{1}</span> ' + '<span data-notify="message">{2}</span>' + '<div class="progress" data-notify="progressbar">' + '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' + '</div>' + '<a href="{3}" target="{4}" data-notify="url"></a>' + '<button type="button" aria-hidden="true" data-notify="dismiss" class="close"><span>×</span></button>' + '</div>' }); } jquery event when form will be submited $('.notifications-demo > .btn').click(function(e){ //e.preventDefault(); var nFrom = $(this).attr('data-from'); var nAlign = $(this).attr('data-align'); var nIcons = $(this).attr('data-icon'); var nType = $(this).attr('data-type'); var nAnimIn = $(this).attr('data-animation-in'); var nAnimOut … -
error for ImportError: No module named 'PyQt4' in Django
I am working Django app I want to create graph in django view using plot When I import from matplotlib import pylab as plt it thorws an error as below File "/home/akashk/anaconda3/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/home/akashk/projects/tutorial/website/urls.py", line 3, in <module> from . import views File "/home/akashk/projects/tutorial/website/views.py", line 21, in <module> from matplotlib import pylab File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pylab.py", line 274, in <module> from matplotlib.pyplot import * File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/pyplot.py", line 114, in <module> _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/__init__.py", line 32, in pylab_setup globals(),locals(),[backend_name],0) File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt4agg.py", line 18, in <module> from .backend_qt5agg import FigureCanvasQTAggBase as _FigureCanvasQTAggBase File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5agg.py", line 15, in <module> from .backend_qt5 import QtCore File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/backend_qt5.py", line 31, in <module> from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__ File "/home/akashk/anaconda3/lib/python3.5/site-packages/matplotlib/backends/qt_compat.py", line 124, in <module> from PyQt4 import QtCore, QtGui ImportError: No module named 'PyQt4' I am having PyQt5 with latest version. How can I avoid calling module PyQt4 Thanks -
Multiple keys vs dictionary in memcache?
What is a better approach? Having multiple keys or having a dictionary? In my scenario I want to store songs in a country basis and cache that for further access later on. Below I write the rough pseudocode without disclosing too many details to keep it simple. The actual songs will most probably be IDs from songs in a database. Many keys approach cache.set("songs_from_city1", city1_songs) cache.set("songs_from_city2", city2_songs) .. Dictionary approach cache.set("songs_by_city", { 'city1': city1_songs 'city2': city2_songs .. }) .. -
Can I generate a REST service from a GraphQL schema?
I'd like to build a Django app with both a GraphQL endpoint and a REST API. Maintaining both separately would be too much of a pain; I'm looking for a good way to only maintain the GraphQL service and have the REST endpoints generated automagically. Does anyone know about a good way to do this? I know there are ways to build a GraphQL server on top of REST endpoints, but I'd rather have it the other way around, as the REST API requirement might go away in the future. -
'by_the_time', expected 'empty' or 'endfor'. Did you forget to register or load this tag?
I got an error, TemplateSyntaxError at /app/detail/3/ Invalid block tag on line 23: 'by_the_time', expected 'empty' or 'endfor'. Did you forget to register or load this tag? . I wrote in detail.html like {% load static %} <html lang="en"> <body> <div id="comment-area"> {% for comment in post.comment_set.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span> {{ comment.name }} <span class="lead text-muted">{{ comment.created_at }}</span> <a href="{% url 'blog:recomment' comment.pk %}">REPLY</a> </h5> {{ comment.text | linebreaksbr }} {% for recomment in comment.recomment_set.all %} <div class="media m-3"> <div class="media-body"> <h5 class="mt-0"> <span class="badge badge-primary badge-pill">{% by_the_time recomment.created_at %}</span> {{ recomment.name }} <span class="lead text-muted">{{ recomment.created_at }}</span> </h5> {{ recomment.text | linebreaksbr }} </div> </div> {% endfor %} </div> </div> {% endfor %} </div> </body> </html> in models.py class Comment(models.Model): name = models.CharField(max_length=100, blank=True) text = models.TextField() target = models.ForeignKey(POST, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) I think the number of if-else statement of template tag is correct,and I wrote {% load static %} so I really cannot understand why this error happens.When I deleted <span class="badge badge-primary badge-pill">{% by_the_time comment.created_at %}</span>,the error was also deleted... How should I fix this? -
Django slow server response with file large file upload
Python 3.6 and Django 1.11 I am sending from a client multipart/form-data to a django form, the model looks like class Document(models.Model): name = models.CharField(max_length=300) author = models.CharField(max_length=100) file = models.FileField(upload_to='files/') and i am using class based views class DocumentCreate(CreateView): model = Document form_class = DocumentForm success_url = reverse_lazy('document_list') and a classic ModelForm: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = '__all__' Im on the embedded server, wich i knwow may perform poorly, but when i send a 2gb files with the client, is see that the file is created after ~10 seconds (and databases entries etc..) but the client have to wait 10 more seconds for the django server to send the response (seen with wireshark). I can even keyboardinterupt the client script before the django server answer, with no consequences to the data transmission. Here is the client script in gross: fich = open('2go', 'rb') sess = requests.session() data = {'author': 'gerard', 'csrfmiddlewaretoken': csrftoken, 'name': 'gerard'} sess.post('http://127.0.0.1:8000/post_document', data=data, files{'file': fich}) I got another script which streams the multipart data, but its slower and also have to wait for the server response. So the question is, why is the server answer so slow, although everything is already uploaded … -
Django rest framework: not updating the results immediately
I am using Django 2.0 and Django rest framework 3.7.3. I have updated the published_date field of an object but when i retrieve the list of posts it does not reflect. I think its showing the old results postsclass PostListAPIView(ListAPIView): today = timezone.now() def get_queryset(self): today = timezone.now() articles = Article.objects.all() return articles.filter(publish_date__lte=today).order_by('-publish_date')[:30] serializer_class = PostSerializer class PostSerializer(serializers.ModelSerializer): publish_date = serializers.DateTimeField(format="%Y-%m-%d %H:%M UTC") class Meta: model = Article fields = "__all__" what to do so that the changes are reflected immediately in the api -
Converting pandas dataframe to json is slow
Converting a csv (of 50k rows) to json for eventual consumption by a Django template is quite slow. I was wondering if I was converting it correctly or if there's a better way to do this. First few rows of the csv are: tdate,lat,long,entity 3/6/2017,34.152568,-118.347831,x1 6/3/2015,34.069787,-118.384738,y1 1/1/2011,34.21377,-118.227904,x1 3/4/2013,33.81761,-118.070374,y1 Am reading this csv in views and rendering the request this way: def index(request): df = pd.read_csv('app/static/data.csv') df.tdate=pd.to_datetime(df.tdate) df['Qrt'] = df.tdate.dt.quarter df['Yr'] = df.tdate.dt.year jzon=df.groupby('entity')[['lat','long','Qrt','Yr']].apply(lambda x: x.to_dict('records')).to_json(orient='columns') return render(request, 'app/index.html', {'jzon': jzon}) -
order a child model with respect to parent model in Django
I have Problem and Solution model defined in my models.py. Solution has a foreignkey to the Problem model. That is, a problem can have many solutions. I want to create urls like www.example.com/problem/problem_id/solution/solution_number/ where problem_id describes the primary key of Problem model and solution_number describes the order in which the solution was posted for a particular problem. In other words, if a solution is first solution to a given problem, its order should be 1 and second solution to the same problem gets an order 2. This will allow me to access a solution to particular problem like Solution.objects.get(problem=problem, order=order) -
Cannot query "____": Must be "Article" instance
models.py from django.db import models from django.urls import reverse class ProductCategory(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.name class Meta: verbose_name = 'Category' verbose_name_plural = 'Categories' class Product(models.Model): name = models.CharField(max_length=128, blank=True, null=True, default=None) description = models.TextField(default=None) processor = models.CharField(max_length=300, blank=True, null=True, default=None) video = models.CharField(max_length=300, blank=True, null=True, default=None) ram = models.CharField(max_length=300, blank=True, null=True, default=None) disk_space = models.CharField(max_length=300, blank=True, null=True, default=None) oS = models.CharField(max_length=300, blank=True, null=True, default=None) video_trailer = models.CharField(max_length=10000, blank=True, null=True, default=None) img = models.CharField(max_length=10000, blank=True, null=True, default=None) category = models.ManyToManyField(ProductCategory, blank=True, default=None) is_active = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) slug = models.SlugField(primary_key=True, max_length=250, unique=True, default=None) def __str__(self): return '%s' % self.name def get_absolute_url(self): return reverse('product', args=[str(self.slug)]) class Meta: verbose_name = 'Game' verbose_name_plural = 'Games' class ProductDownload(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) link = models.CharField(max_length=10000, blank=True, null=True, default=None) is_active = models.BooleanField(default=True) number = models.PositiveIntegerField(blank=True, default=True) def __str__(self): return '%s' % self.product.name class Meta: ordering = ['number'] class Meta: verbose_name = 'Download Link' verbose_name_plural = 'Download Links' class ProductImage(models.Model): product = models.ForeignKey(Product, blank=True, null=True, default=None, on_delete=False) image = models.CharField(max_length=10000, blank=True, null=True, default=None) is_main = models.BooleanField(default=False) is_active = models.BooleanField(default=True) def __str__(self): return '%s' % self.product class Meta: verbose_name = 'Product Image' verbose_name_plural …