Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Run this python script with Django?
// this is a matrix code of python and how should i run it in django enter code here X=[[1,2,3],[4,5,6],[7,8,9]] Y=[[9,8,7],[6,5,4],[3,2,1]] result=[[0,0,0],[0,0,0],[0,0,0]] for i in range(len(X)): for j in range(len(X)): result[i][j]=X[i][j]+Y[i][j] for r in result: print(r) -
Passing kwargs from CBV to Form in Django
I have a ModelForm which needs a user passed in so that the queryset can be updated. I am overriding the __init__ method as such: def __init__(self, *args, **kwargs): # override init to get user's casino's EmployeeType queryset self.user = kwargs.pop('user') print(self.user) super(MemoForm, self).__init__(*args, **kwargs) self.fields['receiver'].queryset = EmployeeType.objects.filter( casino=self.user.casino ) In the View I have a get and a post method. I am trying to pass the **kwargs in as such: class VideoUploadView(LoginRequiredMixin, View): """ Display a form for uploading videos. """ form_class = VideoUploadForm success_url = '/videos' template_name = 'videos/video_upload.html' def get(self, request, *args, **kwargs): form = self.form_class() return render( request, self.template_name, {'form': form, 'user': self.request.user} ) In a CreateView you are able to use the get_form_kwargs method to pass in the **kwargs. How is it done in a normal View? Should we use the __init__ method? The way shown above does not seem to work. -
Django admin site add html link
admin.py @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): list_display = ('Student_Users', 'School_Year', '<a href="#">Report</a>') ordering = ('Education_Levels',) list_filter = ('Student_Users',) I just want that to add the html link in the adminsite then if the admin click the "report" it will filter what studentenrollmentrecord selected to html file -
What is the term / process in Databases for cascade-like behavior (see details)?
I'm newer to databases and have done tons of research over the last few months and so now everything I've learned is getting muddled. I'm trying to find the terminology for this particular behavior in databases so I can further research it. I'm currently writing a program in Django models I'd like to implement this on but I'd like to also know the terminology generically so I can research it elsewhere as well. Say you have a couple tables, one (we'll call A) who contains a foreign key matching the primary key in another (we'll call B). And let's say if a value in a certain field of A changes, then another field in B needs to change as well (not necessarily to the same value as A). Pretty much what I'm looking for is a way to create functions that are always called if some predefined event happens in one table, that can execute some sort of check, or logic or whatever needs be to determine what the new value should be in another table and then make sure that value is implemented in said other table). I've found lots of things that seem to elude to this sort … -
Django: how to add links to my admin site
I have this code in my admin-site, @admin.register(StudentsEnrollmentRecord) class StudentsEnrollmentRecord(admin.ModelAdmin): #inlines = [InLineStudentsSubmittedDocument,InLineStudentsEnrolledSubject,InLineStudentsStudentsPaymentSchedule] list_display = ('Student_Users', 'School_Year') ordering = ('Education_Levels',) list_filter = ('Student_Users',) admin site i just want to add an html_link here and filter what studentenrollmentrecord selected -
why is get this error ?Manager isn't available; 'auth.User' has been swapped for 'user.User'
I know it's an old question and there are lots of posts replying to this question but I didn't find anywhere mentioning why we get this error. I know that importing get_user_model and User=get_user_model() do the job but why we need to do this? I import like this: from user.models import User and also my user model extends abstractbaseuser. why Django can't understand this is my user model and should use this one? I have also changed the settings like this: AUTH_USER_MODEL = 'user.User' -
Do post-save signals run absolutely after the save method?
I have a form_valid method in a view which contains a couple methods: for group in groups: username = list( users.models.Employee.objects.filter( employee_type=group ) ) for user in username: form.instance.unread.add(user) user.send_sms('memo') user.send_email('memo') which send emails and SMS messages during the creation of a memo. The issue with this is that there is a lag in redirecting to the next page due to these 2 operations running. I assume this is because they wait for a full response from the API I am using. If these methods are put inside post-save signals will they run in the background and allow redirect instead of waiting for a response from the API? -
How to serve protected files on python django development server?
Whoa there brave adventurers!! The first one to answer this question will be rewarded a kings ransom of points!! ::shifty_eyes:: Goal: Use django's view level permissions so people can't search the source code to view a file without the proper view level permissions. I'm using nginx's X-Accel-Redirect header with a URI to serve a video on the page that was uploaded by me, from a particular directory I chose in the projectcontainer on the development server. What I tried so far: All static and media files serve fine from static. Variations of using the os module, and django's File() class/subclasses to get the absolute uri of the file, and put it in the src="{{ uri }}" attribute in the html. Reading every webpage I could on this for 8 hours, like this one, and every related nginx documentation like this one, among many others. Starved myself. Faceplanted my keyboard. Danced around the fire. Begged the computer gods. Cried myself to sleep. All to no avail brave adventurer!! Do any brave souls know why my spells aren't working??? I'm aware the development server is not nginx, but I thought it might have functionality like it. What I have: project structure: projectcontainer/ … -
How to structure models for forecasting app?
In Django, I am looking for recommendations on how to structure models for a forecasting app that is similar to a polling or quiz app - but not quite. Overview of requirements: (1) A quiz will have multiple questions. (2) Questions can take multiple forms - True or False, Multiple Choice with 3 options, Multiple choice with 4 options, etc. (3) Users submit forecasts (aka answers) for each question in the form of probabilities with the constraint that the total probability is 100%. So, for question #1 with three options A-C a user might forecast A: 30%, B: 50%, C: 20% (4) Each question has 1 correct answer. [Questions are scored using Brier scoring, but that is not essential for this discussion.] I am familiar with the Django tutorial polling app and have looked at multiple quiz apps, but none of them address my problem. If I use the structure of the Django polling tutorial with the number of choices being indeterminate, then I can't figure out how organize a user's forecast to a question - since that forecast must have a probability for each choice and the probabilities must add up to 100%. If I create multiple models of … -
django ugettext_lazy not working inside save models.Model
This is my model: class Friend(AbstractBaseModel): """ Table for the friendship of the pets """ STATE_CHOICES = Choices( (0, 'accepted', _('accepted')), (1, 'requested', _('requested')), ) source = models.ForeignKey('pets.Pet', on_delete=models.CASCADE, verbose_name=_('original pet'), help_text=_('the pet that the friendship comes from'), related_name="%(app_label)s_%(class)s_source_items") reciever = models.ForeignKey('pets.Pet', on_delete=models.CASCADE, verbose_name=_('reciever pet'), help_text=_('the pet that the friendship comes at'), related_name="%(app_label)s_%(class)s_reciever_items") state = models.IntegerField(default=0, null=True, blank=True, choices=STATE_CHOICES, verbose_name=_('state of the friendship')) history = HistoricalRecords() class Meta: verbose_name = _('Friend') verbose_name_plural = _('Friends') unique_together = ['source', 'reciever'] def __str__(self): return f'{self.source} friendship with {self.reciever}' def _the_friendship_petition_is_newly_created(self): return self.id is None and self.state == self.STATE_CHOICES.requested def _the_friendship_is_accepted(self): return self.id is not None and self.state == self.STATE_CHOICES.accepted def save(self, force_insert=False, force_update=False, using=None, update_fields=None): if self._the_friendship_petition_is_newly_created(): super().save(force_insert, force_update, using, update_fields) pet_creator = get_object_or_404(RelationshipUserPet.objects.filter(creator=True), pet_id=self.reciever_id) content_of_title = _(f'Your pet {self.reciever} has recieved a friendship invitation') title = (content_of_title[:47] + '..') if len(content_of_title) > 47 else content_of_title WebNotification.objects.create(title=title, description=_(f'Your pet {self.reciever} has recieved a friendship invitation of {self.source}'), # TODO: this url notification needs to change url=WebNotificationRoute.objects.get( fix_id=WebNotificationRoute.FIX_ID_CHOICES.friendship_accept ), user_id=pet_creator.user.id, params=f'{{"friendship": {self.id}, "source": {self.source_id},' f'"reciever": {self.reciever_id}}}', read=False) This is my django.po #: apps/friends/models.py:54 #, fuzzy, python-brace-format #| msgid "Your pet {self.reciever} has recieved a friendship " msgid "" "Your pet {self.reciever} has recieved a … -
GraphQL AttributeError: module 'graphene' has no attribute 'Heroes'
i am a beginner with Django & GraphQL, i had a problem the at first step, i can not reach to GraphiQL, i had an error ImportError at /graphql/ Could not import 'traindjango.schema.schema' for Graphene setting 'SCHEMA'. AttributeError: module 'graphene' has no attribute 'Heroes'. "traindjango/heroes/schema.py" import graphene from graphene_django import DjangoObjectType from .models import Heroes class HeroesType(DjangoObjectType): class Meta: model = Heroes class Query(graphene.ObjectType): heroes = graphene.Heroes(HeroesType) def resolve_links(self, info, **kwargs): return Heroes.objects.all() "traindjango/traindjango/schema.py" import graphene import heroes.schema class Query(heroes.schema.Query, graphene.ObjectType): pass schema = graphene.Schema(query=Query) "traindjango/traindjango/settings.py" INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'heroes', 'graphene_django', ] GRAPHENE = { 'SCHEMA' : 'traindjango.schema.schema', } "traindjango/heroes/models.py" from django.db import models class Heroes(models.Model): name = models.CharField(max_length=100, verbose_name='Name') power = models.IntegerField(default=0) city = models.TextField(max_length=100, verbose_name='City' ,null=True, blank=True) Could you please help me what i can do it? Thanx a lot -
Re-display table after form submit
Good afternoon, I have a simple Django 2.2 application for users to check in equipment they have checked out. A table of users and items they have checked out dominates the top of the page. On the very bottom row, a single text/submit form. I would like this to happen: user enters equipment id and submits page re-displays with: name removed from table (if success), form cleared, success/fail message next to cleared form. I am close. All of my logic and queries work, my item gets checked back in. However, the page re-renders with no table of users, just the form with the old data still in it. views.py class EquipmentReturn(View): def get(self, request, *args, **kwargs): # get checked out items for display table -this works form = ExpressCheckInForm(request.POST) return render(request, 'eq_return.html', context={'master_table': master_table, 'form': form} def post(self, request): if request.method == 'POST' form = ExpressCheckInForm(request.POST) if form.is_valid(): # this checks the item back in (or not) and creates messages-works else: form - ExpressCheckInForm() return render(request, 'eq_return.html', context={'form': form} I know there is a better way to do this. For instance, my form would not appear until I declared it in the get function. How can I make all of … -
Django calling same view out of multiple views for a template
I have a template which calls multiple views. But for some reason, the same view is being called. I'm not able to figure it out. Template : schedule.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Schedule Page</title> </head> <body> <h1>Today's Schedule </h1> <b>Scheduled Appointments:</b> <div> {% for p in schedule %} <p> {{p.id}} {{p.name}} {{p.surname}} {{p.appointment_time }} </p> {% if p.status == "Arrived" %} <p>Patient Arrived</p> <!-- <button>See Patient</button> --> <form action="{% url 'see_patient' p.id %}" method="post"> {% csrf_token %} <input type="hidden" name="appid" value="{{ p.id }}"> <input type="submit" value="See Patient" class="btn btn-primary"> </form> {% elif p.status == 'In Session' %} <p>In Progress</p> <form action="{% url 'complete' p.id %}" method="post"> {% csrf_token %} <input type="hidden" name="app_id" value="{{ p.id }}"> <input type="submit" value="Complete" class="btn btn-primary"> </form> {% elif p.status == 'Complete' %} <p>Completed</p> {% else %} <p>{{p.status}}</p> {% endif %} {% endfor %} </div> </br> </body> </html> views.py: def see_patient(request, appid): print("See Patient", appid) app = CheckAppointments() app.update_appointment_status(appid, {'status' : 'In Session'}) appointment_obj = Appointments.objects.get(appointment_id = appid) appointment_obj.status = "In Session" update_wait_time(request) return redirect('/schedule/') def appointment_complete(request, app_id): print("Complete:", app_id) app = CheckAppointments() app.update_appointment_status(app_id, {'status' : 'Complete'}) appointment_obj = Appointments.objects.get(appointment_id = app_id) appointment_obj.status = "Complete" appointment_obj.save() … -
How do I connect MySQL to my Django Project
I have a Django app with running on the default sqlite3 database, but I want to connect it to a MySQL database. I have created a database in my cpanel host and configured the settings in my Django app settings as follows: 'ENGINE': 'django.db.backends.mysql', 'NAME': 'my_db_name', 'USER': 'my_username', 'PASSWORD': 'my_db_user_password', 'HOST': 'my_domain', 'PORT': '3306', This is the response I get when I try to run my app with the settings above: django.db.utils.OperationalError: (1045, "Access denied for user 'my_username'@'a_certain_IP' (using password: YES)") This certain_IP is not my host Shared IP Address. I am not good with SQL, I need help please. Is there anywhere I need to set to allow password login? -
Does Django CMS support taxonomies or tags?
I am studying Python and Django, my final goal is to create an administration panel that manages 2 things: "dynamic article / item" (which can create types of forms to enter). "dynamic taxonomies / tags" (which can create categories or groupers of the data "of the form type"). I have seen the documentation of DjangoCMS but I cannot find the names of these concepts, could you guide me? thank you -
How to access a Django form field through HTML?
This is how the Django form is written in the html file: <form method='post' action="{%url 'getNewAbstracts' %}"> {% csrf_token %} {{editViewAbstractForm|crispy }} <input type="submit" value="Submit" class="btn btn-primary"> <br><br> </form> This is the form written in the django forms file: class editViewAbstract(forms.ModelForm): class Meta: model = abstract `enter code here` fields = ['abstractTitle', 'publicationDate', 'pmid', 'leadAuthor', 'publicationName', 'abstractBody', 'keywordIdList', 'currentStatus'] I am trying to access a specific field of the form for example the field abstractTitle and change the value of that input box through the html file. The reason is that I need to change the fill-text in the Django form every time that a html button is clicked without reloading the page. What is the best way to do this? Thank you for your help. -
add shortcut or link from storage inside static folder in django
When users upload an image it will be placed in : BASE_DIR/storage folder. My static files are placed in: BASE_DIR/static folder Here is my root folder (BASE_DIR) in following image: I have created a shortcut ( or link) from storage folder inside the static folder, and you can see my static folder in following image: I have a test.jpg inside my storage folder and when i try to open the file in my browser using following url: http://localhost:8000/static/storage/test.jpg I get a 404 error: 'storage\test.jpg' could not be found but when I copy and paste the storage folder without creating a shortcut (or link) browser displays image successfully. my question is how can I display the image using a shortcut or link from storage inside static folder? -
Display different inputs based on one form field in Django
So I've got my models - 'product' from CartItem is a foreign key of a Product: class Product(models.Model): name = models.CharField(max_length=64, verbose_name=_('Name')) type = models.ForeignKey('pizza.ProductType', related_name='pizza', on_delete=models.CASCADE, verbose_name=_('Type')) size = models.ForeignKey('pizza.Size', related_name='pizza', on_delete=models.CASCADE, verbose_name=_('Size')) price = models.DecimalField(max_digits=4, decimal_places=2, verbose_name=_('Price')) class CartItem(models.Model): user = models.ForeignKey('accounts.CustomUser', related_name='carts', on_delete=models.CASCADE, verbose_name='User') product = models.ForeignKey('pizza.Product', related_name='carts', on_delete=models.CASCADE, verbose_name=_('Product')) quantity = models.SmallIntegerField(verbose_name=_('Quantity')) toppings = models.ManyToManyField('pizza.Topping', related_name='cart_items', blank=True) extras = models.ManyToManyField('pizza.SubExtra', related_name='cart_items', blank=True) And I want to use a CreateView to add a product to user cart, but I want a user to choose Product Type and Product Size and based on that selection I would add a product to cart, so instead of the field 'product' in form, I would like user to see 'product__type' and 'product__size' in the form. I tried with something like that, but it doesn't work: class CartItemForm(forms.ModelForm): class Meta: model = CartItem fields = ['product__type', 'product__size', 'quantity', 'toppings', 'extras'] Is there a way to do it? -
In Django with Django REST Framework, what is the best way to update old objects when adding new field?
I have a database with a model that I'm updating by adding a new field. When I added the field, all the old objects in the database populated that field with an empty string value. I need these fields to have values. In the future, objects be forced to contain a value by either specification or a default value. What is the best way to update this field for the old objects? I have a couple ideas but I'm not sure if one is 'proper.' Again, this is something that only needs to be done once, as all future objects will have all required data. Enable PUT by adding the UpdateModelMixin to the ViewSet, then disable PUT (I do not want PUT permanently allowed) Create some sort of migration script to do the updates for me. Something I'm missing? -
Switch from using one database to having one for auth and one for everything else
Within my Django app I currently only have one DB, under settings it is default. What I want to do is port over all of the Auth tables created by Django to a separate database, Ill say SiteAuth for now. I have copied all of the auth tables over to the SiteAuth db, but I am not sure how to integrate those changes within the site. I know I am going to have to add another db the databases section of settings, But I am not sure how to do the migrations, or how to specify which database I want to query. How would I do the migrations? how would I specify which database I want to query? how would my models.py change? Thanks for all the help! -
Django Urls - Template Issue {% url '' %}
When I started Django I used 1.11 and since then upgraded to 2.0. My urls worked and had no problems and I would imagine something has been updated but I keep going over the documentation and I can't see where the issue is. From what I've seen my url in template is correct, even though I have also tried with '' and still get the same issue. NoReverseMatch at /admin/dashboard Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/admin/dashboard Django Version: 2.2.6 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Exception Location: /home/bridgetsarah/.local/lib/python3.5/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673 Python Executable: /usr/bin/python3 Python Version: 3.5.2 Python Path: ['/home/bridgetsarah/voyage/bridgetsarah', '/usr/lib/python35.zip', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/usr/lib/python3.5/lib-dynload', '/home/bridgetsarah/.local/lib/python3.5/site-packages', '/usr/local/lib/python3.5/dist-packages', '/usr/lib/python3/dist-packages'] Server time: Fri, 25 Oct 2019 19:26:43 +0000 Any information, would be much appreciated. <ul> 24 <li> <i class="fas fa-tachometer-alt"></i> <a href="#"> Dashboard </a> </li> 25 <li><i class="fas fa-tasks"></i> <a href='#'> Projects </a> </li> 26 <li><i class="fas fa-users"></i> <a href="{% url client %}"> Clients </a> </li> 27 <li><i class="fas fa-server"></i><a href='#'> Servers </a> </li> 28 </ul> 29 from django.urls import include, path , … -
Python / Django: Make a lookup / database query inside a model class
What is the right way to lookup a table and use its last value as a value in a new model class? Something like this: class MyClass(models.Model): id = models.AutoField(primary_key=True) obj = MyClass.objects.latest('id') my_field = models.IntegerField(default=(obj+1)) -
Django built-in tags encoding '?' to '%3F'
I'm trying to do a pagination that passes in ?page={{ page_num }} into the end of the url. This is what I'm trying to do and this is what the output is: $('#prev-page').click(() => { window.location.pathname = "{% url 'xadmin:get_deposits' %}?page={{ page_no|add:'-1' }}" }); $('#next-page').click(() => { window.location.pathname = "{% url 'xadmin:get_deposits' %}?page={{ page_no|add:'1' }}" }); Expected URL: http://localhost:8000/xadmin/deposits/?page=1 Actual URL: http://localhost:8000/xadmin/deposits/%3Fpage=1 -
Trouble opening a WEBSOCKET connection between Angular 2+ client and DJANGO backend
I am trying to open a websocket connection from my angular 2+ app with my Django backend using Django Channels. I went through this tutorial: https://www.youtube.com/watch?v=RVH05S1qab8 and managed to get everything working with the javascript portion written inline in a Django html template. But I am having issues simply opening a websocket connection when I migrated the front-end chat form to a separate angular 2 app. Both font-end and backends are hosted locally. Front End - Chat Form Template <div *ngFor="let message of thread.messages"> <div>{{message.message}}</div> </div> <form #formData [formGroup]="form"> <div class="form-group"> <input formControlName="messageInput" #msgInput type="text" class="form-control" id="newMessage" placeholder="Type a message"> </div> <button (click)="onSubmit($event)" type="submit" class="btn btn-primary">Send</button> </form> </div> Front End - Chat Form Component otherUser: User; me: User; threadId: number; thread: Thread; endpoint: string; socket: WebSocket; form = new FormGroup({ messageInput: new FormControl("") }); get messageInput() { return this.form.get('messageInput'); } getThreadById(id: number) { this._chatService.getThreadById(id).subscribe(thread => { console.log("response: thread found", thread); this.thread = thread; }, error => { console.log("error", error); }); } getEndpoint() { let loc = window.location let wsStart = "ws://" if (loc.protocol == "https:") { wsStart = 'wss://' } this.endpoint = wsStart + loc.host + loc.pathname; return this.endpoint; } constructor(private _activatedRoute: ActivatedRoute) { } ngOnInit() { this._activatedRoute.params.subscribe(params => { … -
Django's rest/login returns wrong user model fields after login
I have created a custom user model using AbstractUser class which is working fine. To login a user i am using rest_auth package. on using url /auth/login, i am able to login the user, but the json that i am getting after login contains fields first_name and last_name which is not included in my custom user model i analyzed parent classes and found that serializer.py file in rest_auth package returns user model on verifying the credentials through authenticate method. i am not able to understand how authenticate method is working model- from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): username = models.CharField(unique=True,max_length=30) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.email class UserProfile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE,related_name='profile') photo=models.ImageField(upload_to='uploads',blank=True,null=True) city=models.CharField(max_length=50,blank=True,null=True) dob=models.DateField(blank=True,null=True) firstname=models.CharField(max_length=50,blank=True,null=True) lastname=models.CharField(max_length=50,blank=True,null=True) serializer- from rest_framework import serializers from .models import User,UserProfile class UserProfileSerializers(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('photo','city','dob') class UserSerializers(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializers(required=True) class Meta: model = User fields = ('id','username','email','first_name','last_name','password','profile') def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user=User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user,**profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile print('hello') print(profile) instance.username = validated_data.get('username',instance.username) instance.email = validated_data.get('email',instance.email) instance.first_name = …