Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django field edit on creation (value on creation, not update)
I want to create a field, that it's value can be set on creation only (via admin) and can't change later. The use is for accounting accounts, that sets currency, and cannot be changed later. editable=True, but only on update, not creation. Is such a thing possible? Thanks -
Rpi.Gpio in django view
How would I go about adding and using the Gpio pins for starter lighting a simple led from the website, I even read in one article that it is due to the wsgi. I've searched many times but i don't get much material for it in django. If there is any material, example or code you can point me to, it would be really helpful. Source(Article): https://www.foobarflies.io/python-on-the-pi-how-to-run-a-flask-gpio-web-service/ -
Python TypeError: 'AutoField' object is not iterable
I'm trying to write field values from a Django model instance to a csv file and I'm using the following code, where image is an instance of the model Image. I'm trying to do this without specifically naming the field names. with open(output_file, "a") as outfile: writer = csv.writer(outfile) writer.writerow([item.value for item in image._meta.get_field(field.name)] for field in image._meta.get_fields()) #writer.writerow([field.name for field in Image._meta.get_fields()]) outfile.close() When I use the commented out line I get the field names which is what I expected. I'm now trying to get the actual field values and I've got the new writerow. This is giving me TypeError: 'AutoField' object is not iterable -
Django ImageField: full or relative path?
I try to implement pictures uploading and processing in my Django project. The problem is with path for ImageField: Option 1. If I use path relative to the media folder, then image.url nicely returns /media/img_name.jpg, and Django handles the pictures correctly. But I cannot use image.width property, it leads to the error: SuspiciousFileOperation The joined path (/user_test/3d55d527-109d-4a07-b0f6-4de0304d41f6.jpg) is located outside of the base path component (/Users/Aivan/Desktop/Code/MyProject/media) Option 2. If I use full path, then I can easily access the image.width property. But image.url returns full path added to the media folder: http://127.0.0.1:8000/media/Users/Aivan/Desktop/Code/MyProject/media/user_test/8f3219cd-0333-4488-9d29-2c5506707afb.jpg Question: What should I do in order to properly access both image.url and image.width? Of course, I can always set up full path and add save the relative path in some CharField, or add an own method for relative URL extracting, but probably such solutions are bad. I guess, that's because Django uses relative paths for media files, but to deal with images it uses Pillow which needs full paths... Maybe it's a bug? My picture class: def path_user_photo(instance, filename): return 'user_{0}'.format(instance.account.user.username) class Photo(models.Model): image = models.ImageField(upload_to=path_user_photo) name = models.CharField(max_length=32, unique=True) And it's static method for images uploading: @classmethod def create_file(cls, fl, user, written_name, ext): folder = '/user_{0}'.format(user.username) … -
Django says database locked, but it is not
I am running a Django app in a test environment on my on PC with a sqlite database. Lately I have problems when trying to use my app, because when I perform several actions, at some point the app just gives the error 'database is locked' and I cannot perform any actions what so ever. I tried several actions I found in How do I unlock a SQLite database? like renaming the database, copying the database and restarting the computer but none of it seems to unlock the database. The only thing I can do then is completely remove the database and create a new one. The weird thing is that I have no problems altering the database via the shell, or via a different database viewer (like DB browser for SQLite). Only when I try to make changes to the database via my front-end or the admin page I get a 'database is locked' error (I cannot even login on my app). Which makes my suspect that the database is not really locked but something else might be going on. There are different moments in time when the database gets locked, but I do have a migration that bulk … -
reading json into django error
I'm passing a context variable, x, into a template from a Djano view. It is a list of strings x = ['Braselton', 'Buford'] Then I am using an ajax function to pass that variable back to a django view. The problem is when I retrieve that variable in a python view with the following code: new_x = request.GET['x'] print(new_x) I see the following: ['Braselton', 'Buford'] I've tried json.loads(request.GET['x']) and I keep getting the following error json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1) Any help is much appreciated -
Dockerized Django app not collecting static files on Heroku
While Heroku's Django documentation states that collectstatic is run automatically, that does not appear to be the case for Dockerized Django apps. When deploying, static files are never collected and thus never served by Gunicorn/Whitenoise. I have tried many things to overcome this, including but not limited to explicitly created the STATIC_ROOT directory, running the container as root, and executing shell scripts to run collectstatic, all with no luck. Furthermore, if I run one-off workers or enter the server shell and explicitly run collectstatic, the files do not persist. It seems that this process needs to be done for each dyno instance--and thus needs to be done automatically. Thus far, the only way I have been able to serve static files in this environment is by collecting the files myself and putting them in a specified STATIC_ROOT directory, but this isn't exactly ideal. Furthermore, it leads to issues with serving some static files locally, or results in me needing to have multiple instances of the static files in the repository (though a script could be written to handle this, it doesn't seem ideal). I would love to know what I am either doing wrong, or a better way of approaching … -
Struggling to iter over attributes in Django 2.0
Here is my code: class Product(models.Model) : name = models.CharField(max_length=150) price = models.DecimalField(max_digits=15, decimal_places=10) category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True, null=True) date = models.DateField(auto_now=True, auto_now_add=False) collection = models.ForeignKey(Collection, on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=100) is_featured = models.BooleanField(default=False) descripition = models.TextField() is_published = models.BooleanField(default=True) attributes = models.ManyToManyField('Attribute') def __str__(self) : return self.name class Meta : ordering = ("-date",) class ProductVariant(models.Model) : sku = models.CharField(max_length=120, unique=True) name = models.CharField(max_length=120, blank=False, null=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) for attri in product.attributes : attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name}) class Meta : ordering = ("name",) def __str__(self) : return self.product.name + self.name class Attribute(models.Model) : name = models.CharField(max_length=120) def __str__(self) : return self.name class Meta : ordering = ("name",) class AttributeVariant(models.Model) : name = models.CharField(max_length=120) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE, related_name='values') class Meta : ordering = ("name",) def __str__(self) : return self.name What I'm trying to do : In the ProductVariant Class, I'm trying to iter through the product attributes and to assign to each of them a field ForeignKey to AttributeVariants to get the values of this specific attribute. It corresponds to the code below: for attri in product.attributes : attri.name = models.ForeignKey(AttributeVariant, on_delete=models.CASCADE, limit_choices_to={'attribute.name': attri.name}) However, when I try to run python manage.py makemigrations, I … -
Conditional update_or_create with django
Test model class Room(models.Model): """ This stores details of rooms available """ name = models.CharField( null=False, blank=False, max_length=100, help_text='Enter the name of the room' ) capacity = models.PositiveIntegerField( null=False, blank=False, help_text='Enter the number of person\'s the room can accommodate' ) created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) I want to update the model if it exists and its modified_at time is less than say x time otherwise just create the model. For reference here it the raw sql I want django to execute. INSERT INTO room VALUES (1,'2018-04-30 18:15:32.96468+04:30','2018-04-30 18:15:32.96468+04:30','Room-A',30) ON CONFLICT(id) DO UPDATE SET capacity=10 WHERE room.modified_at < '2017-04-30 18:15:32.96468+04:30'; Also I would like to know if the SQL query I'have written is atomic or not -
NoReverseMatch at /polls/1/
I am following Django 2.0 tutorial Part4 and encounter the error: NoReverseMatch at /polls/1/ Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls\\/(?P<question_id>[0-9]+)\\/vote\\/$'] The urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] The views.py, I followed the official tutorial strictly step by step: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from django.urls import reverse from .models import Question, Choice def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, "polls/detail.html", {'question':question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): #Redisplay the question voting form return render(request, 'polls/detail.html', { 'question':question, 'error_message':"You did'nt select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I cannot locate the bug. -
403 forbidden error in access log
I am new to stackoverflow. I have configure one of my site on nginx on Ubuntu. This site developed with django. After configure site, This is opening on window but on mac/iphone getting error 403 forbidden. I have check in error log on server this is blank. but in access log as below. 94.101.133.115 - - [01/May/2018:12:23:10 +0530] "POST / HTTP/1.1" 403 33 "-" "Opera/9.80 (Windows NT 5.1; U; en) Presto/2.10.289 Version/12.01" -
Django Query: filtering Decimal('NaN') value?
This is my model: class DailyPrice(models.Model): date = models.DateField() close = models.DecimalField( max_digits=15, decimal_places=2, ) I'd like to get all DailyPrice objects whose close field is Decimal('NaN'). (I can check Decimal('NaN') below query example) >> DailyPrice.objects.last().close Decimal('NaN') What I tried is DailyPrice.objects.filter(close__isnull=True) But it doesn't return anything.... How can I implement this? -
Django Mass Update/Insert Performace
I'm receiving financial data for approximately 5000 instruments every 5 seconds, and need to update the respective entries in the database. The model looks as follows: class Market(models.Model): market = models.CharField(max_length=200) exchange = models.ForeignKey(Exchange,on_delete=models.CASCADE) ask = models.FloatField() bid = models.FloatField() lastUpdate = models.DateTimeField(default = timezone.now) What needs to happen is the following: After new financial data is received, check if an entry exists in the database. If the entry exists, update the ask, bid and lastUpdate fields If the entry does not exist, create a new entry My code looks as follows: bi_markets = [] for item in dbMarkets: eItem = Market.objects.filter(exchange=item.exchange,market=item.market) if len(eItem) > 0: eItem.update(ask=item.ask,bid=item.bid) else: bi_markets.append(item) #Bulk insert items that does not exist Market.objects.bulk_create(bi_markets) However executing this takes way too long. Approximately 30 seconds. I need to reduce the time down to 1 second. I know this can be done as I do the same wth custom SQL code in .NET in under 100ms. Any idea how to improve the performance in Django? -
DRF API requires CSRF on POST in Angular App, works in Postman
I have a simple endpoint in my API (Django Rest Framework). When I try to make a HTTP POST requests in Postman, it works perfectly fine. However, in my Angular 5 app, when I do POST request to the same endpoint, I get Http 403 error with CSRF missing error: CSRF verification failed. Request aborted. My API viewset (api/views.py): class EventViewset(viewsets.ModelViewSet): serializer_class = EventSerializer def get_queryset(self): return Event.objects.filter(server__organization=self.request.user.organization) My angular app works on localhost:4200 -
Evaluate multiple querysets in a single db call
Lets suppose I have a list of unevaluated querysets: q_list = [a.objects.all(), b.objects.all(),...] I want to evaluate all of them at once in a single database call. I can iterate over the list and evaluate them individually like this: evaluated_q_list = map(list, q_list) But that will make multiple db queries. Is it possible to do this in a single db query using Django ORM? -
Django Model inheritance for efficient code
I have a Django app that uses an Abstract Base Class ('Answer') and creates different Answers depending on the answer_type required by the Question objects. (This project started life as the Polls tutorial). Question is now: class Question(models.Model): ANSWER_TYPE_CHOICES = ( ('CH', 'Choice'), ('SA', 'Short Answer'), ('LA', 'Long Answer'), ('E3', 'Expert Judgement of Probabilities'), ('E4', 'Expert Judgment of Values'), ('BS', 'Brainstorms'), ('FB', 'Feedback'), ) answer_type = models.CharField(max_length=2, choices=ANSWER_TYPE_CHOICES, default='SA') question_text = models.CharField(max_length=200, default="enter a question here") And Answer is: class Answer(models.Model): """ Answer is an abstract base class which ensures that question and user are always defined for every answer """ question = models.ForeignKey(Question, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) class Meta: abstract = True ordering = ['user'] At the moment, I have a single method in Answer (overwriting get_or_update_answer()) with type-specific instructions to look in the right table and collect or create the right type of object. @classmethod def get_or_update_answer(self, user, question, submitted_value={}, pk_ans=None): """ this replaces get_or_update_answer with appropriate handling for all different Answer types. This allows the views answer and page_view to get or create answer objects for every question type calling this function. """ if question.answer_type == 'CH': if not submitted_value: # by default, select the … -
Offline bootstrap not working with django 1.11.11 app
please aid...has anyone encountered this same issue? Bootstrap 4 not working offline on django 1.11.11. But it works fine when i use a cdn. I have tried all the settings and followed the documentation..still doesn't work.....am thinking if django has made it mandatory to use cdn instead of serving offline during development. -
For some reason google oauth2 can signup into same user with different gmail emails
Sometimes when user signups with his gmail account to my service and then he signups with his G Suite account, both emails create record in UserSocialAuth model but to same django User. Can someone help me understand why this happens and how to avoid it? I need both gmail accounts have separate django accounts. I am using social-auth-app-django https://github.com/python-social-auth/social-app-django -
Django messages.success don't work
I create a message in my forms.py def clean(self): request = self.request data = self.cleaned_data email = data.get("email") password = data.get("password") qs = User.objects.filter(email=email) if qs.exists(): # user email is registered, check active/ not_active = qs.filter(is_active=False) if not_active.exists(): ## not active, check email activation link = reverse("account:resend-activation") reconfirm_msg = """Go to <a href='{resend_link}'> resend confirmation email</a>. """.format(resend_link = link) confirm_email = EmailActivation.objects.filter(email=email) is_confirmable = confirm_email.confirmable().exists() if is_confirmable: msg1 = "Please check your email to confirm your account or " + reconfirm_msg.lower() raise forms.ValidationError(mark_safe(msg1)) email_confirm_exists = EmailActivation.objects.email_exists(email).exists() if email_confirm_exists: msg2 = "Email not confirmed. " + reconfirm_msg raise forms.ValidationError(mark_safe(msg2)) if not is_confirmable and not email_confirm_exists: raise forms.ValidationError("This user is inactive.") user = authenticate(request, username=email, password=password) if user is None: raise forms.ValidationError("Invalid credentials") login(request, user) self.user = user return data And when I use a simple html it works well and show the message in my screen: {% block content %} <h1>Login</h1> <form method='POST'> {% csrf_token %} {{ form }} <button type='submit' class='btn btn-default'>Submit</button> </form> {% endblock %} But when I use a more 'complex' html the message "Please check your email to confirm your account or " just do not appear: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- … -
Django Prepopulate HTML MultieChoice Field
What's the best way to prepopulate a multiple choice select field. In my view, I'm adding the context the values for the field. def get_context_data(self, *args, **kwargs): context = super(UserProfileUpdateView, self).get_context_data(*args, **kwargs) context['mystates']=user.states output Alaska, Arizona, Alabama, Hmtl page <div class="form-group"> <label for="id_states">Add State 2:</label> <select name="states" id="id_states" multiple="multiple"> {% include "accounts/snippets/states_drop_down_options.html" %} </select> </div> state_drop_down_options.htmlm <option value="AL">Alabama</option> <option value="AK">Alaska</option> <option value="AZ">Arizona</option> <option value="AR">Arkansas</option> <option value="CA">California</option> -
it is better to make table for each individual column that has options or make options tuples inside model class in django
I am using Django 1.11 and mysql for a web database. I have table for cars ads post. This table has many columns such as title, price, time of the posted ads, and so on, there are many columns for car features like type, condition, cylinders, fuel. Each column of them has many choices. for example, for status there are choices of (excellent, very good, good, poor). For fuel gas, diesel. For cylinder choices are 3,4,5,6,8,12. And so on. I have two options to implement this. 1- The first option is to make table for cars contain columns that does not have options like title. Then connect this table to other tables (table for type, model, fuel, cylinders, and so on). Then connect each table to the main cars table in many to one relationship. 2- The second option is to make tuples inside Django model have these choices and make fields inside the main table instead of making every column individual table and then connect them through foreign key. My question is that, which option is more effective from the prospective of: 1- Performance and speed 2- Easy to make forms, and to write and save to database the … -
React Cannot read property state of undefined with API call
I'm trying to get a simple API call working, where the component calls the API as its mounting and sets the state to be rendered. But when I try to get the state to change an object in it, it says that the state is undefined. TypeError: Cannot read property 'state' of undefined class SpellGrid extends React.Component { constructor(props) { super(props); this.state = { value: '', spacing: '16', username: 'admin', password: 'notpassword', description: '', remember: false, spell: { name: '', school: '', }, }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.mapApiToState = this.mapApiToState.bind(this); } mapApiToState() { // I've tried with all of the axios code in here. } componentDidMount() { axios .get("http://localhost:8000/api/spells/1") .then(function(response) { console.log('response', response); let fields = response.data[0].fields; // THIS IS THE LINE THAT IS ERRORING let spell = Object.assign({}, this.state.spell); spell.name = fields.Name; spell.school = fields.School; console.log('spell', spell); this.setState({spell}); console.log('state.spell', this.state.spell); //console.log('state', this.state); }) .catch(function(error) { console.log(error); }); console.log('state', this.state); } handleChange = name => event => { this.setState({ [name]: event.target.value, }); }; onSubmit = (event) => { event.preventDefault(); this.props.onSubmit(this.state.username, this.state.password) }; handleSubmit(e) { console.log('Form state: ', this.state); e.preventDefault(); } render() { const {classes, theme} = this.props; const { spacing } = this.state; return ( <div>{this.state.spell.name}</div> ); … -
Passing Javascript variable as an argument to django custom template tag
I have been staring at my project for so long moving things around and trying methods I have been looking through the internet to solve this problem but I still can't work this one out. I'm making a website using Django framework to make a booking system. What I'm getting is an error saying 'NoneType' object is not subscriptable Basically the whole thing works when run() function in custom_tags.py doesn't have a parameter. I need to pass a parameter to insert in to my sql query to store and find data. The {% run id %} gives me the NoneType error. booking.html <table style="width: 100%""> <tr> <th>Appointment</th> <th>Date</th> <th>Time</th> <th>Book</th> </tr> {% for element in data_list %} <tr> <td>{{element.appointment_id}}</td> <td>{{element.Date}}</td> <td>{{element.Time|time:"H:i"}}</td> <td><button name="checks" id="{{item.appointment_id}}" value="{{element.appointment_id}}" onclick="clicked(this.value, this.id)">Book Lesson</button></td> </tr> {% endfor %} </table> <script type="text/javascript"> function clicked(value, id) { if (confirm('Confirm booking? \n \n' + value)) { alert("Appointment Booked!"); {% load custom_tags %} {% run id %} <!-- this gives me the NoneType error --> location.reload(); //reloads page } else { return false; } } </script> custom_tags.py from django import template import MySQLdb register = template.Library() @register.simple_tag #inserting to bookings table after student books lesson def run(booking_id): client = MySQLdb.connect("localhost", … -
Django - get_redirect_url() causes Page not found (404)
I'm trying to implement favorite feature so that user can choose favorite stores. I'm currently referencing the video https://www.youtube.com/watch?v=pkPRtQf6oQ8&t=542s and stuck with the beginning. When I try to move to the url https://www.fake-domain.com/my-domain/like, it throws the error message saying No Store matches the given query. So, I guess self.kwargs.get("domainKey") this snippet seems to throw the error, but I don't know why. I'm not sure if I'm showing my codes enough, so please let me know I need to show more. models.py class Store(models.Model): ... domainKey = models.CharField(max_length=100) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) ... urls.py url(r'^(?P<store_domainKey>.*)/$', views.detail, name='detail'), url(r'^(?P<store_domainKey>.*)/like/$', views.StoreLikeRedirect.as_view(), name='like'), views.py class StoreLikeRedirect(RedirectView): def get_redirect_url(self, *args, **kwargs): store_domainKey = self.kwargs.get("domainKey") print(store_domainKey) obj = get_object_or_404(Store, pk='store_domainKey') return obj.get_absolute_url() -
Django AutoComplete Light not working with OneToOne Field
I am trying to add auto-complete for the OneToOneField in Django admin using django-autocomplete-light. This field is available in Django Rest Framework's auth_token model. class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) models.py from rest_framework.authtoken.models import Token class CustomAuthTokenModel(Token): search_fields = ['user', ] def __str__(self): return str(self.user) views.py from dal import autocomplete from rest_framework.authtoken.models import Token class AuthUserAutocompleteView(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Token.objects.all().order_by('user__username') if self.q: qs = qs.filter(user__username__icontains=self.q) return qs admin.py from django.contrib import admin from rest_framework.authtoken.models import Token from rest_framework.authtoken.admin import TokenAdmin from .forms import AuthUserForm class CustomTokenAdmin(TokenAdmin): form = AuthUserForm admin.site.unregister(Token) admin.site.register(Token, CustomTokenAdmin) forms.py from dal import autocomplete from .models import CustomAuthTokenModel class AuthUserForm(autocomplete.FutureModelForm): class Meta: model = CustomAuthTokenModel fields = ('user', ) search_fields = ['user__username'] widgets = { 'user': autocomplete.ModelSelect2(url='autocomplete_auth_user') } And in urls.py file, I have: url('^autocomplete_auth_user/$', AuthUserAutocompleteView.as_view(), name='autocomplete_auth_user') I am pretty sure, I must be missing something, because I can't see the user names while entering the form in admin panel for auth token. Let me know what I am missing. I am using Django 1.11 and django-autocomplete light 3.2.10.