Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to update Django in visual studio 2017
I am trying to setup Visual Studio 2017 for Django Development but the Django (1.9) version is old, How can I update it to latest version (>= 2.0). -
Can't find race conditions
I'm making an exercise on Django and I have problem. I'm sorry, guys, it's very stupid question, but people said to me, that this code has race conditions, and can't find where. I tried to find it for a long time, but still can't find all of it. Please, help me to find it views.py class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.select_related().all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.select_related().all() serializer_class = GroupSerializer class ProfileViewSet(viewsets.ModelViewSet): queryset = Profile.objects.select_related().all() serializer_class = ProfileSerializer class NoticeViewSet(viewsets.ModelViewSet): queryset = Notice.objects.select_related().all().order_by('pub_date') serializer_class = NoticeSerializer class IndexView(generic.ListView): template_name = 'exchange/index.html' context_object_name = 'latest_notice_list' @transaction.atomic def get_queryset(self): return Notice.objects.select_related().order_by('-pub_date') class DetailView(generic.DetailView): model = Notice template_name = 'exchange/detail.html' class NewView(generic.CreateView): model = Notice form_class = NoticeForm template_name = 'exchange/new.html' @transaction.atomic def form_valid(self, form): form.instance.author = User.objects.select_for_update().get(id=self.request.user.id) return super(NewView, self).form_valid(form) @transaction.atomic def get_success_url(self): return reverse("exchange:detail", kwargs={'pk': self.object.pk}) class EditView(generic.UpdateView): model = Notice form_class = NoticeForm template_name = 'exchange/new.html' @transaction.atomic def form_valid(self, form): form.instance.author = User.objects.select_for_update().get(id=self.request.user.id) return super(EditView, self).form_valid(form) @transaction.atomic def get_success_url(self): return reverse("exchange:detail", kwargs={'pk': self.object.pk}) class UserNoticesView(generic.ListView): template_name = 'exchange/user_notices.html' context_object_name = 'notices' @transaction.atomic def get_queryset(self): return Notice.objects.prefetch_related().filter(author=self.request.user) class AddMoneyView(generic.UpdateView): model = Profile form_class = ProfileForm template_name = "exchange/add_money.html" @transaction.atomic def get_success_url(self): return reverse("exchange:index") @transaction.atomic def form_valid(self, form): form.instance.user = User.objects.select_for_update().get(id=self.request.user.id) … -
Django - Social Auth (Request URL is showing http instead of https)
I have intergrated SSL certificate in my application and i have https in my site but in django social auth the Request URL goes only with http. I know the Twitter does not allow requests from http. Link : http://humbusy.tk/social-auth/login/twitter/ My site has https but the request goes with http .Why ? and How do i resolve it ? Thanks . -
Doing multiple inserts/updates for multiple models in Single Database hit in Django REST and Django
I have 2 Models in Django. ModelA and ModelB. Here is the code for both these models.(This is just example code.) class ModelA(models.Model): # Single Insert name=model.CharField(max_length=100) class ModelB(models.Model): # Multiple Insert model_a=models.ForeignKey(ModelA,on_delete=models.CASCADE) address=models.CharField(max_length=250) Now how can i insert data in both these models using a single Database Query(i.e Database should be hit only once) using ORM in Django.More specifically is it possible to do this via Django REST serializers cause it can handle the CRUD operations in an optimized manner. I know that i can do this via multiple serializers but that will lead to the databse getting hit multiple times or i can also do this via stored procedures in MySQL. -
python or Django settings file like c#
I'm currently writing on an app in Django, I have a lot of variables so I would like to save their current values in a file and use them when I needed them, there was a settings file in c# which was really great for this purpose, is there such thing in Django or python? -
passing a parameter from html page url mapping to the views in django
front.html <div class="row"> <a href="{% url 'emp_pay_list' Information_technology %}"> <div class="col-md-6 col-sm-6 col-lg-3"> <div class="dash-widget clearfix card-box" style="height: 200px;"> <span class="dash-widget-icon"><i class="fa fa-cubes" aria-hidden="true"></i></span> <div class="dash-widget-info"> <h3>20</h3> <span>Information Technology</span> </div> </div> </div></a> <a href="{% url 'emp_pay_list' sales %}"> <div class="col-md-6 col-sm-6 col-lg-3"> <div class="dash-widget clearfix card-box" style="height: 200px;"> <span class="dash-widget-icon"><i class="fa fa-users" aria-hidden="true"></i></span> <div class="dash-widget-info"> <h3>7</h3> <span>Sales Team</span> </div> </div> </div> </a> The above code is the front end part html here i want pass a parameter into the urls.py by clicking a box and depends on the parameter which we pass the data should be fetched . urls.py url(r'^list_of_employees/<string>/$', views.Pay_slip_list , name='emp_pay_list'), this is the code which i am using for urls.py for this the parameter should be passed. views.py def Pay_slip_list(request, department): hello = employees.objects.select_related('employee_name', 'employee_auth').filter(department=department) return render(request, 'hr/emp_pay_list.html', {'hello': hello}) And this is the views.py part where i am fetching data from the database based on the string/parameter passed after clicking the box. -
Setting session variable on click
I've got a popup message with a close button at the top. If the user clicks the close button, they should never see the message again while on the site. If they don't click the close button, they will see it on the top of each page on the site. When the user clicks the close button, I want to set request.session['promo'] to 0. On subsequent page loads on the site, if request.session['promo'] == 0, I will not show the popup message. What is the best way of setting a session variable on click in django? Thanks for the direction! -
ImportError: cannot import name 'include'
I am following django official tutorial-01. After editing the "urls.py" file I got this error "ImportError: cannot import name 'include' ". I have searched it here and got two solutions. To update the django version To include include in polls urls - "from django.conf.urls import include" I have tried this two solutions, but getting error still now. Please give me any solution. Here is the screenshot of the terminal - enter image description here My django version is - 1.11.0 -
Dynamic database routing
Am having multiple databases. Out of which one database contains all the credentials for other databases, I want to store that particular database information in settings.py through out the application and using those credentials from that database information I want to route to respective database. How this is possible in Django. -
custom foreign key values based on constrain
I have a model as: PRODUCT_EXPIRY MODEL: product_id = model.IntegerField() expires_in = model.IntegerField() --days count And another model as: PRODUCT: product_id = model.IntegerField() expires_in = model.IntegeField(blank=True) --days count name = model.CharField() price = model.FloatField() ...other fields What I want is, let a store add products, and here expires_in (days count) of product is optional, he can choose to add it manually while adding product or if he doesn't, then the expire in is entered from product_expire model, mapping via product_id. BUT consider following cases: Milk X has 3 days of expiry. Milk Y has 60 days of expiry. Cocoa powder has 6 months of expiry date. When a store enter a product, lets suppose he gets it at least after 10 days from manufacturing date. So the expire_in shall be 60-10 days for products which has expiry greater than say 30 days. Where as milk van delivers milk daily, so product with expiry less than 30 days will have expiry as same without any change. How can I do so? Eg: Suppose we know coke expires in 1 month, so if a store forgets to enter expiry date, the automatic expiry date added shall be 20 days. So as later … -
Give same random value to the random.seed() until a certain condition is met
def get_unanswered_questions(self, quiz,answers,correct_answers,lev): answered_questions = self.quiz_answers \ .filter(answer__question__quiz=quiz) \ .values_list('answer__question__pk', flat=True) answerss=list(answers) correct_answerss=list(correct_answers) list_of_ids= list(quiz.questions.values_list('id', flat=True)) if len(answerss)==0: global rand_num rand_num=randint(0,1000) random.seed(rand_num) random.shuffle(list_of_ids) clauses = ' '.join(['WHEN id=%s THEN %s' % (pk, i) for i, pk in enumerate(list_of_ids)]) ordering = 'CASE %s END' % clauses questions = quiz.questions.filter(pk__in=list_of_ids).exclude(pk__in=answered_questions).extra(select={'ordering': ordering }, order_by=('ordering', )) I don't know the proper way of doing it. I need to generate a random number when the len(answerss)=0 and pass that same number to the random seed value so that the order of questions remain same for each execution of get_unanswered_questions until it gets to another condition when len(answerss)==0 again. Is there any way of doing it? -
Pulling Django variable data using Python
I am currently working on a project to grab live match data for eSports (yeah I'm a nerd, aren't we all?). So I am pulling HTML from a page and checking if my favorite team is playing and if so, go the page and check the scores every few minutes to get updates. The part I am now having trouble with is getting the names of teams and the match ID's. The reason for this is because when I grab the HTML data, inline JS variable names are included instead of their values which is what I need. Here is an example of what I am talking about: <div class="col-xs-12 schedule-{[{schedule.state}]}" ng-if="schedules.length&gt;0" ng-repeat="schedule in schedules track by schedule._id"> I need a way to grab the value of "schedule.state". Hopefully you guys can help. Also if there is already a similar solution I would be happy to be directed to it! Cheers! EDIT I have just realized through a little more researech that the variables are not JS but Django. Given the same problem just on how to get Django variable data instead of JS. -
Best way to filter().update() in django while handling zero rows?
Is there a good way to filter().update() in django while handling zero rows? Lets say I want to run: Dogs.objects.filter(noise='woof').update(animal_name='dog') This throws and error if Dogs.objects.filter(noise=‘woof’) returns zero results. Now I can do: dogs = Dogs.objects.filter(noise='woof') if len(dogs) > 0: dogs.update(animal_name='dog') But is just seems a bit messy, any better ways to do this? Something like: Dogs.objects.filter(noise='woof').update_if_rows(animal_name='dog') -
How to save custom class object in Model field in Django
I am using OAuth2 Authentication in my Django app and after authorization, I want to save the credentials somewhere. I am trying to save those in my Django Model. Here is the code till now: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) country = models.CharField(max_length=30, blank=True) credentials = CustomCredential( client_id='', access_token='', expires_in_seconds=0, scopes='', grant_type='' ) def __str__(self): return self.user.username tasks.py: def authorise(user, auth, redirect_url): if auth: session = auth_flow.get_session(redirect_url) credentials = session.oauth2credential print("Before:", user.profile.credentials.client_id) # blank value here user.profile.country = country # some variable user.profile.credentials = credentials print("After:", user.profile.credentials.client_id) # client_id is printed user.save() return "/" else: auth_flow = AuthorizationCodeGrant( CLIENT_ID, SCOPE, CLIENT_SECRET, 'http://localhost:8000/auth' ) return auth_flow.get_authorization_url() With this code, I can change the field values country, credentials but the change is saved only for country and not for the credentials field (has blank value for client_id) Can anyone help me in solving this problem? Or please suggest if there is some better way to store authorization credentials in Django. -
Django not downloading file
I want the user to download a file and see its password, for that I've created a template home.html which user can see after login through login.html everything is working correctly eg. login, logout, displaying the password and creating a download link to the file. But the file is not being downloaded. Below is the code from the files: Views.py def login(request): username = str(request.POST['username']) password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: userid = User.objects.get(username=username) useractive = userid.is_active userid = userid.id email_verify = UserProfile.objects.get(username_id=userid) email_verify = email_verify.email_verified if userid and email_verify is True: CertPassword = GenerateCertificate.objects.get(username_id=userid) CertPassword = CertPassword.cert_password filepath = '/certs/' + username + '.p12' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) certlocation = BASE_DIR + os.path.join(BASE_DIR, filepath) return render(request, 'vpn/home.html', { 'CertPassword': CertPassword, 'username': username, 'certificate': filepath, 'certlocation': certlocation}) else: return HttpResponse( '<center>Login Failed, have you activated your account?</center>') else: return HttpResponse( '<center>Login Failed<br><a href="/">Login again?</a></center>') home.html {% block content %} this is home, your certificate password is: <b>{{ CertPassword }}</b><br> Download your certificate here: <a href="file://{{ certlocation }}" target="_blank">{{ username }}</a> <br> <a href="/logout/">Logout</a> {% endblock %} I havnn't used the Media_url as I've used for some other purpose and I don't know how to … -
Django 2 Redirect to next page on form submit
I have a Django 2 app paginating through one large 'place' record at a time, and the template adds some radio button sets to each, which the user can check in the course of validating what's in the record. I wrap each record in a form, and upon submit I want to a) create a new record from those selections in a separate 'review' model/table, and b) redirect to the paginator's next page. I have no trouble creating the new record from the form radio inputs, then redirecting to a confirmation page. The problem is how to redirect to the same view/template but advancing the page. I tried redirecting to the same view but a different url: path('place/', views.place, name='place'), path('place/next', views.place, name='placenext'), then parsing the request object in the view, but this fails without error: def place(request): paginator = Paginator(place_list, 1) req = request.path page = request.GET.get('page') if req[-4:] == 'next': records = paginator.get_page(str(int(page)+1)) else: records = paginator.get_page(page) context = { 'records': records, 'page': page } return render(request, 'review/place.html', context=context) I also tried many other things, including inserting ?page= in a few ways, but it's fumbling in the dark because there is no indication in docs of how to … -
MySQL not saving on test_ database when testing using Django
Curently I've a Django Application and it works perfect when using their models on my project. But when I try to create a new object when testing on my test.py it wont save tried debug and it returns for object.pk (None) Here is my code: class TestUserViews(TestCase): def test_authentication_success(self): try: cc = Country.objects.create(name="Lala Land") print('country saved') print(cc.id) print('-----') except Exception as error: print(error) try: ll = Language.objects.create(name="English") print('language saved') print(ll.id) print('-----') except Exception as error: print(error) try: user = User.objects.create(first_name="user name", last_name="user last", phone="000123455", identification="0000001123", address="my house", country=cc, language=ll, email="email@mail.com", password=hash_string("mypassword")) print('User saved') print(user.id) except Exception as error: print(error) -
Django Celery Beat, change app name in admin
When we create our custom apps we can assign verbose_name in myproject/myapp/apps.py: class MainConfig(AppConfig): name = 'main' verbose_name = 'My Own Verbose Name' I have added django_celery_beat into my INSTALLED_APPS and now my admin page has this app: How I can change this Periodic Tasks app name? -
Django - Host a website on a Lan Network
I've been working on a website for the past month, and now its time for me to host the django website onto a private server. Is there a detailed method on how I'm supposed to host the website onto a specific IP address assigned to my system? This is my first time dealing with hosting a server and i dont know much about it. Also, once i host it, How do i change the link from being the IP address to an actual link like "12345678.com" or something like that? (The website should be hosted in such a way that only the people who are in the same network/lan connection should have access to the website.) I have wamp on the system and the system has a Windows Server OS (if this info helps) -
Django storing data and use it in app level
When ever am running the manage.py file I get the information from some external url. How to store that information in memory and how to use that throughout the application in django -
Multithreading for Django
I'm writing web application for get data from Database(MySQL) to file.csv using Django Framework.I can get data but It take so much time to get complete successfully.I don't want to wait for get data finish. I want to continue to next activity but background still get data from Database. My setup : Python 3.6.5, Django 2.1 Thank you for helping me. -
How to Assign a Task to a user in Django-Vieflow
class HelloWorldFlow(Flow): process_class = HelloWorldProcess ### Here I start the process where i enter some text start = ( flow.Start( CreateProcessView, fields=["text"] ).Permission( auto_create=True ).Next(this.approve) ) ### Here i update the process view with the user name which i obtained from "asignedto"- which consist of all the user in a drop down approve = ( flow.View( UpdateProcessView, fields=["asignedto"] ).Assign(lambda act: act.process.created_by) .Permission( auto_create=True ).Next(this.task_assign) ) ### Below is the code where i am facing difficulty i am not able to know how to pass the user name in the .Assign() ### This one works .Assign(username="Debasish"), however i want to assign the user based on previous workflow which is approve, where i selected from the drop down ### This one do not work .Assign(username=this.approve.owner) task_assign= ( flow.View(AssignTaskView) .Assign(this.approve.owner) .Next(this.check_approve) ) ### Below this its working check_approve = ( flow.If(lambda activation: activation.process.approved) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request ).Next(this.end) ) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text) -
How to get a model by modelname in django template
I have model LandingSnippet that contains attribute ...model = CharField()..., and it is related to context keyword (for example cars in context below) I have next code in my view def GeneratedLanding(request): snippets = LandingSnippet.objects.all().filter(view_on=True).order_by('order') context = { 'snippets':snippets, ... 'cars':Car.objects.all(), # this is cars ... return render(request,'qlanding/generateindex.html',{'context':context}) how i can get querySet cars that is in context by keyword cars as a string for example {{context}} prints {'snippets': <QuerySet [<LandingSnippet: Snippet1Title>, <LandingSnippet: 2 - about - Лучшая служба развозки детей>]>, 'services': <QuerySet []>, 'cars': <QuerySet []>, 'faqs': <QuerySet []>} and {{snippet.model}} prints cars QUESTION: How can i get the {{ context.cars }} ? I think something like context[snippet.model] where snippet.model='cars' i want push it inside another template when include {% if snippet.module %} {% with "qlanding/snippets/module/"|add:snippet.module|add:".html" as path %} {% include path with model=context[snippet.model] %} # But this is incorect while rendering {% endwith %} {% endif %} -
'WSGIRequest' Error when trying to create Model object based on username for logged in User
AIM I am attempting to set the Alarm.username to the username of the currently logged in User. The problem is identical to another query, although my code is a little different in that I extract location details for each Alarm object. How,and where, do I integrate the line: username=User.objects.get(username=self.request.username) in my code? ERROR Request Method: POST Request URL: http://jqlc3gdp.apps.lair.io/login/set_alarm/ Django Version: 2.0 Exception Type: AttributeError Exception Value: 'WSGIRequest' object has no attribute 'username' Exception Location: /mnt/project/weather_alarm/views.py in get_user_timezone, line 94 CODE Models.py class User(models.Model): """ Model representing each User """ username = models.CharField(max_length=20, unique=True) password = models.CharField(max_length=30, validators=[MinLengthValidator(8)]) email = models.EmailField(max_length=254) first_name = models.CharField(max_length=20) last_name = models.CharField(max_length=20) class Alarm(models.Model): """ Model representing each Alarm """ alarm_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.ForeignKey(User, on_delete=models.CASCADE, null=True) # null=True is TEMP timezone = models.CharField(max_length=30) city = models.CharField(max_length=30) country = models.CharField(max_length=30) time = models.DateTimeField() temp_conditional = models.BooleanField() surf_conditional = models.BooleanField() temp_max = models.FloatField(blank=True, null=True) temp_min = models.FloatField(blank=True, null=True) surf_max = models.FloatField(blank=True, null=True) surf_min = models.FloatField(blank=True, null=True) Forms.py class SetAlarmForm(ModelForm): ... class Meta: model = Alarm exclude = ['username', 'timezone', 'city', 'country'] Views.py class AlarmCreateView(LoginRequiredMixin, CreateView): model = Alarm form_class = SetAlarmForm template_name = 'weather_alarm/set_alarm.html' success_url = reverse_lazy('weather_alarm:confirm-alarm') login_url = "/login/" def form_valid(self, form): … -
Django:django.db.utils.OperationalError: no such column
The problem is I am making an eCommerce application using Django and using a Products model. First I added the fields title,description and price ran all the commands makemigrations,migrate and everything was working fine. Now I added a field called Image to it and then when going to apply makemigrations it gives an error django.db.utils.OperationalError: no such column: Products_product.image I applied all the proposed solutions to this including deleting the database and again recreating it and also deleting the migrations history from the migrations folder but still they didn't work so I had to again make a new project. Now in new project this imagefield migrations worked fine at my initial migrations , and now i added a field called featured(BOOLEAN FIELD) to mark several products as featured , and now the problem arises again, the same problem that was with that imagefield. django.db.utils.OperationalError: no such column: Products_product.featured I wasted a whole lot of time digging the internet for this problem but none of them are working?Please help