Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django allauth: empty 'signup_url, login_url and logout_url'
Using django 1.11.4 and package django-allauth==0.33.0 Login works fine The default login template 'login.html' contains a link to a signup page: <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> and that works fine but any other page then /account/* its just empty base.html: <div class="nav-wrapper"> <a href="/" class="brand-logo">Logo</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> {% if user.is_authenticated %} <li> Welcome: {% user_display user %}</li> <li><a href="{{ logout_url }}">logout</a></li> {% else %} <li><a href="{{ login_url }}">sign in</a></li> <li><a href="{{ signup_url }}">sign up</a></li> {% endif %} <li></li> </ul> </div> I use the base.html on /accounts/* as well as on the index. on /accounts/* its works fine but on the index the {{ logout_url }} etc are empty. Settings extract: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'debug': DEBUG, 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] Same problem answer didnt help -
In Django, getting next/previous object by date when some share the same date
In Django I have a Letter model: class Letter(models.Model): letter_date = models.DateField(blank=False, null=False) When viewing an individual letter, using a DateDetailView(), I want to show "next" and "previous" links. To get the next/previous Letter I can do this in one of the view's methods (and similar to get next_letter: try: previous_letter = self.model.objects.filter( letter_date__lt=date).order_by('-letter_date')[:1].get() except self.model.DoesNotExist: previous_letter = None That works fine if there's only one Letter per day, but some days have multiple letters, and this code will skip subsequent letters on the same day. How can I ensure next/previous doesn't skip letters? This doesn't sound hard, but my brain is struggling... -
Slug field creation using ID
this the postmodel and trying to create a slug unique field The Slug field creation error str(self.id) is returning "none" where as the seld.title is working correctly class postmodel(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(User,default=None) body = models.TextField() slug = models.SlugField(unique=True) subject=models.TextField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) updated = models.DateTimeField(auto_now=True,auto_now_add=False) @models.permalink def get_absolute_url(self): return ('blog_post_dpetail', (), { 'slug': self.slug, }) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title)+"-"+str(self.id) super(postmodel, self).save(*args, **kwargs) -
django - logging edit event - need to get id of logged in user
I've a product-stock model as given below. TRANSACTION_TYPE=(('I','Stock In'),('O','Stock Out')) class Stock(models.Model): product=models.ForeignKey('product.Product', blank=False,null=False) date=models.DateField(blank=False, null=False,) quantity=models.PositiveIntegerField(blank=False, null=False) ttype=models.CharField(max_length=1,verbose_name="Transaction type",choices=TRANSACTION_TYPE, blank=False, db_index=True) I need to log the update activity on this model, along with the id of the user who updated it. ACTIONS=(('EC','Edit Category'), ('EG','Edit Group'), ('EP','Edit Product'), ('ES','Edit Stock')) class MyLog(models.Model): user=models.ForeignKey(auth.models.User, blank=False) action= models.CharField(max_length=2, choices=ACTIONS, null=False,blank=False) date=models.DateTimeField(blank=False, auto_now=True) data = JSONField() I've the added following code to the Stock model. def __init__(self, *args, **kwargs): super(Stock, self).__init__(*args, **kwargs) if self.pk != None : self.__important_fields = ['product','date', 'quantity', 'ttype', ] for field in self.__important_fields: setattr(self, '__original_%s' % field, getattr(self, field)) field_name='__original_%s' % field def save(self, *args, **kwargs): if self.pk != None : print("Editing") flag=False log=MyLog(user=?,action='ES') log.data=[] for field in self.__important_fields: original=getattr(self, '__original_%s' % field) if original != getattr(self, field): flag=True log.data.append({field : str(original)}) if flag: log.save() else: print("Adding") super(Stock, self).save(*args, **kwargs) This works, when I hard code a user object into the line log=MyLog(user=?,action='ES'). I need to log the id of the user who performed this edit operation. How can I achieve this? Thanks. -
IE11 strips url parameters?
In our Django project, we have 4 hrefs. Each href goes to the same url but has different URL parameters. To differ between them, we need to specify parameter. Unfortunately, IE11 strips these parameters. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>****.com</title> <link ....> <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script> <script src="/static/js/jquery.formset.js"></script> <script src="/static/Flat-UI/dist/js/flat-ui.js"></script> <script> $(document).ready(function () { $('.alert').delay(4000).fadeOut('slow'); }); </script> </head> .... lot of code ... <div class="container"> <div class="col-md-6 top-margin-half"> <a class="btn btn-primary pull-right" style="width: 50%;" href="/dashboard/doklady/vytvorit/?typ=faktura">FA</a> </div> <div class="col-md-6 top-margin-half"> <a class="btn btn-primary col-md-6" style="width: 50%;" href="/dashboard/doklady/vytvorit/?typ=zalohova_faktura">ZALFA</a> </div> .... When user clicks, for example, on ZA href, it takes him to ../dashboard/doklady/vytvorit/ instead of .../dashboard/doklady/vytvorit/?typ=faktura Do you have any idea how to solve this problem? -
Django NotImplementedError: annotate() + distinct(fields) is not implemented
I want to count the total number of specific values in the structure field. Fund.objects.all().exclude(structure__isnull=True).extra(select={'Structure': 'structure'}).values('Structure').annotate(total=Count('structure')).order_by('-total') But before I do, I want to apply distinct() function so that only the objects with distinct id will be used for the query. So i tried something like this: object_list = Fund.objects.all().distinct('id') object_list.exclude(structure__isnull=True).extra(select={'Structure': 'structure'}).values('Structure').annotate(total=Count('structure')) But I get the error: NotImplementedError: annotate() + distinct(fields) is not implemented. How can I achieve this? In Psql: CREATE VIEW distinct_funds as select distinct id, structure from Fund; SELECT count(structure), structure from distinct_funds GROUP BY structure; -
django - form submits information but does not save to database
I've been stuck on this problem for a good bit -- the form is able to submit but will not save to the database. I've even sent an email through the one form, but it won't save. I'm making a CRM and have a contact, communication, and email app. This view has three forms so far, one for each model. The contact form is able to save to the DB. The other two are able to submit but will not save. The two forms not saving can both be redirected back to the refreshed contact detail with their instance and data still available on the form. So it must be storing properly, just not saving. I'm not sure what I'm missing. Let me know if you need me to add other files. views.py---------- def contact_detail(request, contact_id): contact = get_object_or_404(Contact, pk=contact_id) if request.method == 'POST' and 'contact' in request.POST: contactForm = ContactForm(request.POST, prefix='contact', instance=contact) if contactForm.is_valid(): contactForm.save() else: contactForm = ContactForm(prefix='contact', instance=contact) if request.method == 'POST' and 'email' in request.POST: contactForm = ContactForm(prefix='contact', instance=contact) messageForm = MessageForm(request.POST, prefix='email', instance=contact) if messageForm.is_valid(): messageForm.save() form_email = contact.contact_email form_message = messageForm.cleaned_data.get("message") subject = messageForm.cleaned_data.get("subject") from_email = settings.EMAIL_HOST_USER to_email = [from_email] contact_message = "%s" % … -
Retrieve nested dict from Django nested queryset with ForeignKey?
I have a model having a model like this: class Other(models.Model): name = models.CharField(max_length=200) class ModelA(models.Model): name = models.CharField(max_length=200) other = models.ForeignKey(Other, on_delete=models.PROTECT) in my rest API i want to retrieve as JsonResponse a json like this: { "modelA":{ "id":"modelA id automatically assigned by django model", "name":"my modelA name", "other":{ "id":"other thing id also automatically assigned by django model", "name":"other thing name" } } } What is the most "pythonic" way to do it? -
Django: User Reporting System
I wants to create a way in which user can report something to the site admin. Is it a good way to store the url of the page that they are on so that when they click report button from specific page specific url is sent to us? In template we've something like {{ request.build_absolute_uri }} to catch the url of page but how can I make it happen in view to store that url though a form. Also, please suggest me if there's a better way for doing this? Thanks in advance! -
How to get data from all objects using tastypie API?
My goal is to get all data from tastypie API. This API has more than 1.000.000 objects inside! I have created another Django project and a custom "product_import.py" command which should get all data from this API. What should I do to continue getting data from API when I reach the limit? I want to get data from API ['meta']['next'] dictionary to continue collecting objects in another project. Below is an example I created for now and got stuck. api.py # coding: utf-8 from tastypie.resources import ModelResource from tastypie import fields from tastypie.authentication import ApiKeyAuthentication from tastypie.authorization import DjangoAuthorization from .models import Product class UserguideResource(ModelResource): class Meta: resource_name = 'product' allowed_methods = ['get'] fields = ['id', 'name', 'date_added', 'author'] queryset = Product.objects.all() authentication = ApiKeyAuthentication() authorization = DjangoAuthorization() This file is created in different Django project which uses tastypie API from project above. I want to get all data from this API. product_import.py from django.core.management.base import BaseCommand import requests class Command(BaseCommand): """ Import Products from API """ def __init__(self): self.API_KEY = 'API_KEY' self.API_USERNAME = 'keNzi' self.product_api_url = 'http://localhost:8000/api/v1/product' self.limit = 1 self.offset = 0 def get_latest_products_from_api(self, limit, offset): response = requests.get( "{0}?username={1}&api_key={2}&limit={3}&offset={4}".format( self.product_api_url, self.API_USERNAME, self.API_KEY, self.limit, self.offset, ) ).json() return … -
Django unit test AssertionError: 404 instead 200
I'm trying to write a unit test for a view in Django 1.8. I am trying to test a view that is at an address that contains year and month as parameters. This is the address to my view: url(r'^/(?P<year>[0-9]{4})/(?P<month>[0-9]+)$', views.BookingListView.as_view(), name="list"), Here is my test code: def test_booking_list(self): url = reverse('archive:list', kwargs={'year': 2011, 'month': 10}) response = self.client.get(url) self.assertEqual(response.status_code, 200) I recived an error: Traceback (most recent call last): File "path to.../test_views.py", line 16, in test_booking_list self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 EDIT Path to view in browser bar: http://127.0.0.1:8000/en/archive/2011/01 View BookingListView: class BookingListView(ListView, MonthArchiveView): queryset = models.Booking.objects.order_by('-date_start') template_name = 'archive/booking_list.html' date_field = 'date_start' def get_context_data(self, **kwargs): min_year = self.queryset.aggregate(Min('date_start')) max_year = self.queryset.aggregate(Max('date_start')) months_choices = [] for i in range(1, 13): months_choices.append({'number': i, 'name': _(calendar.month_name[i])}) context = super(BookingListView, self).get_context_data(**kwargs) context['mode'] = 'archive' context['years'] = range(min_year['date_start__min'].year, max_year['date_start__max'].year + 1) context['months'] = months_choices context['selected_year'] = self.kwargs['year'] context['selected_month'] = self.kwargs['month'] context['object_list'] = models.Booking.objects.filter(date_start__year=self.get_year(), date_start__month=self.get_month()) context['current_month_name'] = _(calendar.month_name[int(self.kwargs['month'])]) return context -
Only same data is got several times
I wanna parse excel and print out it.I wrote like files = glob.glob('./data/*.xlsx') for x in files: if "$" not in x: print(x) book3 = xlrd.open_workbook(x) sheet3 = book3.sheet_by_index(0) cells = [ ('user_id', 0, 4), ('name', 0, 5), ('nationality', 1, 4), ('domitory', 1, 5), ('group', 1, 6), ] dict_data = OrderedDict() for key, rowy, colx in cells: try: dict_data[key] = sheet3.cell_value(rowy, colx) except IndexError: dict_data[key] = None print(dict_data) So,I got a result like OrderedDict([('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)], [('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)], [('user_id', '1'), ('name', 'Blear'), ('nationality', 'America'), ('domitory', 'A'), ('group', 1)]) Excel is So I really cannot understand why I got only one data several times.I wanna get all data only 1 time each data.How can I fix this?I do not think indent is wrong. -
How to save a modelSerializer that has relations? - django
I want to save a sent json data to db by django-rest-framework. the problem is, not saving the relation and returns error. The bellow snippet is my models: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE) name = models.CharField(max_length=30) family = models.CharField(max_length=50) class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE) I use below serializer for serializing/deserializing the Klass model. class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('pk', 'name', 'family') class KlassSerializer(serializers.ModelSerializer): teacher = ProfileSerializer() class Meta: model = Klass fields = ('id', 'title', 'description', 'teacher') now when I prepare a JSON object and send it to the view, it returns error. the below is the view class: class KlassView(APIView): """for SELECT, INSERT Queries""" def get(self, request, pk): # somthing @csrf_exempt def post(self,request, pk=None): """For Creating A Class""" serializer = KlassSerializer(data=request.data) if serializer.is_valid(): teacher = ProfileSerializer(request.data['teacher']['pk']) serializer.teacher = teacher.data serializer.save() return Response({'data': serializer.data}) else: return Response({'data': serializer.errors}) and the error is: The .create() method does not support writable nested fields by default. Write an explicit .create() method for serializer mainp.serializers.KlassSerializer, or set read_only=True on nested serializer fields. How can I save relation in KlassSerializer in order to save to db? -
How to get "sum" of a column with a condition in Django
I am using django 1.11 and postgresql 9.5. In a view, I am reading a file and inserting data to DB. The table structure is like this.. id | integer user_id | integer percentage | numeric(3,2) After inserting data, I have table like this., id user_id percentage 1 1 9 2 1 50 3 1 4 4 2 12 5 2 23 6 3 46 7 3 33 8 4 87 Now I want to find, sum of percentage of each user, like, user-1 = 63 user-2 = 35 user-3 = 79 user-4 = 87 I went through the documents, and I found aggregation query like, <modelname>.objects.aggregate(Sum('percentage')) but, this will give sum of whole column, I want sum for individual user. How to achieve. -
filter query results without launching a new sql query
With this code I expected that an sql query would run only on 'all_user_videos' and that the subsequent filter would use the results stored in 'all_user_videos' to do the filter. # Get all user videos all_user_videos = Video.objects.filter( author = user ) # User pending videos pending_videos = all_user_videos.filter( status = 'pending_review' ) # Get user Video that need information info_required_videos = all_user_videos.filter( status = 'info_required' ) # Get user video on sale on_sale_videos = all_user_videos.filter( status = 'on_sale' ) context = { "user_member_profile": instance, 'pending_videos' : pending_videos, 'info_required' : info_required_videos, 'on_sale' : on_sale_videos } It seems not to be the case, and that each filter runs a query. How can I make so that pending_videos, info_required_videos and on_sale_videos don't relaunch queries and use result from the query in 'all_user_videos' ? -
TypeError at images/create - __init__() got an unexpected keyword argument 'save'
I don't know what's wrong here. I'm trying to save images from other websites to my database, but I get TypeError at images/create - __init__() got an unexpected keyword argument 'save'. images is an app and create is name of the url. Here's the code urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^create/$', views.image_create, name='create'), ] views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm @login_required def image_create(request): if request.method == 'POST': # Form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # Form data is valid cd = form.cleaned_data new_item = form.save(commit=False) # Assign current user to the item new_item.user = request.user new_item.save() messages.success(request, 'Image added successfully') # Redirect to the newly created item detail view return redirect(new_item.get_absolute_url()) else: # Build form with data provided by the bookmarklet via GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section' : 'images', 'form' : form}) and the forms.py which also contains code to override the save() method from urllib import request from django import forms from django.core.files.base import ContentFile from django.utils.text import slugify from .models import Image class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ('title', 'url', 'description') … -
Prevent autoescaping custom template tags in django
I'm upgrading my old project to latest versions of python/django and am having trouble with custom template tags. Template tag definition: from django import template register = template.Library() def my_tag(*args) -> str: """ returns html code """ register.simple_tag(lambda *x: my_tag("hello world", *x), name='my_tag') Example tag usage: {% my_tag "this no longer works, this autoescapes my code" %} How can I modify my tag definition to prevent autoescaping, so that I don't have to modify templates: {% autoescape off %}{% my_tag "workaround, this doesn't autoescape html" %}{% endautoescape %} -
Django can't edit user profile
I'm trying to make an edit user profile form, my problem is if i don't exclude the user from form it will ask for it, but if i exclude it i'm getting: null value in column "user_id" violates not-null constraint models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) forms.py class UserProfileForm(ModelForm): class Meta: model = UserProfile fields = '__all__' exclude = ('user', ) def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs.update({'class': 'form-control'}) views.py def user_profile(request): data = dict() if request.method == 'POST': form = UserProfileForm(request.POST) if form.is_valid(): profile = form.save(commit=False) profile.save() return redirect('/apps/home') else: form = UserProfileForm() data['form'] = form return render(request, 'core/profile.html', data) profile.html <form class="js-validation-bootstrap" action="" method="post"> {% csrf_token %} {{ form.errors }} <div class="form-group row"> <label class="col-lg-4 col-form-label" for="val-username">First Name </label> <div class="col-lg-8"> <input type="Text" class="form-control" id="val-username" name="first_name" placeholder=""> </div> </div> <div class="form-group row"> <label class="col-lg-4 col-form-label" for="val-username">Last Name </label> <div class="col-lg-8"> <input type="Text" class="form-control" id="val-username" name="last_name" placeholder=""> </div> </div> <div class="col-lg-8 ml-auto"> <button type="Submit" class="btn btn-alt-primary">Submit</button> </div> </div> </form> I don't understand why it gives me that error. -
compilemessages makes i18n crashes
I have a problem when I run python manage.py compilemessages it used to work perfectly fine but today, whenever I do it, i18n won't load on my web pages. I always get the same issue : raise ValueError('invalid token in plural form: %s' % value) ValueError: invalid token in plural form: EXPRESSION I tried to empty my .po files and to rerun compilemessages, and I still get the error. I have absolutely no other clue where to look for. Note: when I go back to any former commit, everything will run fine until I run compilemessages -
Django Bulk Upload to DB with CSV Upload - All are uploaded and only one not
I am trying to upload some big files to my Django DB. When i do that, all of the files are uploaded, and only one is not uploading. There is no error, but the upload is not been made. The one that is not uploading is the last Ofac_Sdn_Comments function. Please note that there is no error and also the DB is not updated accordingly. If someone could help me, I would owe you a lot. Please find below my models: class Ofac_Sdn(models.Model): number = models.IntegerField(blank=True, null=True) name = models.CharField(max_length=200, null=True) b_i = models.CharField(max_length=250, null=True) programe= models.CharField(max_length=250, null=True) more_info = models.CharField(max_length=250, null=True) vessel_call_sign = models.CharField(max_length=250, null=True) vessel_type= models.CharField(max_length=250, null=True) vessel_dwt = models.IntegerField(blank=True, null=True) tonnage = models.IntegerField(blank=True, null=True) vessel_flag = models.CharField(max_length=250, null=True) vessel_owner= models.CharField(max_length=250, null=True) dob_aka= models.CharField(max_length=250, null=True) class Meta: verbose_name_plural = "ofac_sdn" def __str__(self): return ((self.number, self.name, self.programe)) class Ofac_Add(models.Model): number = models.ForeignKey(Ofac_Sdn, on_delete=models.CASCADE) n= models.IntegerField(blank=True, null=True) adresa = models.CharField(max_length=250, null=True) oras_zip = models.CharField(max_length=250, null=True) stat = models.CharField(max_length=250, null=True) ceva = models.CharField(max_length=250, null=True) class Meta: verbose_name_plural = "ofac_add" def __str__(self): return self.number_id, self.adresa , self.oras_zip, self.stat, self.ceva class Ofac_Alt(models.Model): number = models.ForeignKey(Ofac_Sdn, on_delete=models.CASCADE) ceva = models.CharField(max_length=500, null=True) aka = models.CharField(max_length=500, null=True) name_of_aka = models.CharField(max_length=500, null=True) a = models.CharField(max_length=250, null=True) class … -
django - I purchased heroku addons. how to set up?
I wanna deploy my django project to heroku. My project uses channels so I need to set up ASGI based environment. I have two installed add-ons in heroku app. One is Heroku-postgresql and the other is Heroku-redis. And I have two dynos please refer to below picture. I succeeded push django project on heroku git. $ git push heroku master So, I got url address. demo-multichat.herokuapp.com If you access that url, you will face Application error. I got log msg using $ heroku logs. Below is log messages. 2017-09-08T11:54:50.421663+00:00 app[web.1]: 2017-09-08 20:54:50,421 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:54:55.424117+00:00 app[web.1]: 2017-09-08 20:54:55,423 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:00.426387+00:00 app[web.1]: 2017-09-08 20:55:00,426 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:05.428815+00:00 app[web.1]: 2017-09-08 20:55:05,428 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:10.430511+00:00 app[web.1]: 2017-09-08 20:55:10,430 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:15.432112+00:00 app[web.1]: 2017-09-08 20:55:15,431 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:18.486722+00:00 heroku[worker.1]: State changed from crashed to starting 2017-09-08T11:55:20.434001+00:00 app[web.1]: 2017-09-08 20:55:20,433 ERROR Error trying to receive messages: NOAUTH Authentication required. 2017-09-08T11:55:22.996928+00:00 heroku[worker.1]: Starting process with command `python manage.py runworker` 2017-09-08T11:55:23.685971+00:00 heroku[worker.1]: State changed … -
How to get data from DateField format in bootstrap 3 datepicker?
I am trying get a publish date field for my posts using Bootstrap 3 DateTimePicker. I am having problems while synching formats. My model is a datefield: publish = models.DateField() I use django-bootstrap3-datetimepicker class GalleryForm(forms.ModelForm): publish = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS, widget=DateTimePicker(options={ "format": "DD.MM.YYYY", "pickTime": False})) class Meta: model=Gallery fields = [ "title", "slug", "description", "publish" ] I use Class Based Createview: class GalleryCreateView(LoginRequiredMixin, CreateView): form_class = GalleryForm template_name = "galleries/gallery_form.html" success_url = "/galleries/" def form_valid(self, form): instance = form.save(commit=False) return super(GalleryCreateView, self).form_valid(form) and I use crispy forms also in my form templates and a script <form method="post" class="form-inline"> ... {{form|crispy}} ... </form> <script type="text/javascript"> $(function () { $('#id_publish').datetimepicker({ inline: true, icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-arrow-up", down: "fa fa-arrow-down" }, /*remove this line if you want to use time as well */ }); }); </script> how can I fix my datefield format error ? Thanks -
Tables not showing up and migrations not visible after `python manage.py migrate`
I'm following the official tutorial on Django and have run python manage.py migrate in https://docs.djangoproject.com/en/1.11/intro/tutorial02/ . After this, I'd expect some files to show up in polls/migrations, but there is just an empty __init__.py there, and when I run sqlite3 and type .tables or .schema, nothing is output. Still, the python manage.py migrate command seems successful: $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK What's going wrong here? -
How can I write multiple filter in Django
I am confusing how can I write the filter code in my serializers.py. I have the following models. User (AbstractBaseUser) userid = models.CharField(max_length=64, primary_key=True) username = models.CharField(max_length=128) Clinic (models.Model) clinic_id = models.CharField(max_length=8, primary_key=True) clinic_name = models.CharField(max_length=64) Consultation (models.Model) consultation_id = models.AutoField(primary_key=True) clinic_id = models.ForeignKey(Clinic) user = models.ForeignKey(User) Chat (models.Model) chat_id = models.AutoField(primary_key=True) consultation_id = models.ForeignKey(Consultation) DIDRESPONSE_CHOICE = { ('R', 'No'), ('C', 'Doing'), ('F', 'Done'), } did_response = models.CharField(max_length=1, choices=DIDRESPONSE_CHOICE, default='N') ChatDetail (models.Model) chat_no = models.AutoField(primary_key=True) chat_id = models.ForeignKey(Chat) CHATFROM_CHOICE = { ('D', 'Doctor'), ('U', 'User'), } chat_from = models.CharField(max_length=1, blank=True, null=True) chat = models.CharField(max_length=512, blank=True) I want to serialize above data and response to client in JSON format. { 'username': 'Tom Smith', 'clinic_name': 'Adam's clinic', 'consultation_id': 12345678, 'chat_id': 09876543, 'chat_detail' : [ {'chat_no': 11122233, 'chat_from': 'D', 'chat': 'How are you doing today?'}, {'chat_no': 11112234, 'chat_from': 'U', 'chat': 'I have a headache'}, {'chat_no': 11122235, 'chat_from': 'D', 'chat': 'Oh, I'm sorry'}, {'chat_no': 11122236, 'chat_from': 'U', 'chat': 'Can you help me?'}, ] } I made filters in my views.py by using override get_queryset method. But it wasn't not work. So, I tried to write filters in my serializers.py. But it is also didn't work(I don't understand how can I write above requirement filter … -
Putting a bet to record Django model
im working on a social network project and im going to make follower and following to my users and i did it with another Model named Follow class Follow(models.Model): follower = models.ForeignKey(User,on_delete=models.CASCADE,related_name="followers", blank=False,null=False) following = models.ForeignKey(User,on_delete=models.CASCADE,related_name="followings",blank=False,null=False) def __str__(self): return self.follower.username + " is following " + self.following.username and now im gonna put conditions to record, for example somebody can't follow himself or if that record exists, don't record it again Thanks for reading. Comments are Welcomed