Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django existing cookie is not updating
What i am trying to do is updating the existing django cookie that already exist. I am creating a add to cart functionality but unable to add more items in existing cookie. Any help would be praise-able. My code is: def AddToCart(request): id = request.POST.get('id') product = Product.objects.get(pk=id) response = render(request,'index.html') if request.COOKIES.get('product'): request.COOKIES['product'] = {'name':product.name,'price':product.price,'img':product.image.url} else: response.set_cookie('product',{'name':product.name,'price':product.price,'img':product.image.url}, max_age= 14 * 24 * 60 * 60) return response -
admin and user login allow on same browser in django
I have Three types of user Vendor, Customer and Admin, And all are from default django auth User model, Here when Vendor login, then customer get loged in automatic, and when admin logout all others user get logout . This happens on same browser. How to over come this problem.? How to allow customer , vendor and admin login on same browser. My Model: MyUser - class MyUserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email, and password. """ if not email: raise ValueError('Users must have an email address') user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password,**kwargs): """ Creates and saves a superuser with the given email and password. """ print("hello admin") user = self.create_user(email,password=password) user.is_superuser=True user.is_admin = True user.is_staff = True user.save(using=self._db) return user from Peru.choices import * class MyUser(AbstractBaseUser): email = models.EmailField(('email address'), max_length=255, unique=True, blank=False) first_name = models.CharField(('first name'),max_length=50,blank=False,default='') last_name = models.CharField(('Last name'),max_length=50,blank=True,default='') avatar = models.ImageField(null=True, blank=True, max_length=5000)#cloudinary.models.CloudinaryField("Image", default="hkjhkjh") mobile = models.CharField(('Mobile'),max_length=10,blank=False,unique=True) legal_name = models.CharField(('Legal name'),max_length=30,blank=True,null=True) agree_terms_condition = models.CharField(('Agree Term & condition'),default='', max_length=10) mobile_verified = models.BooleanField(('Mobile number Verified'),default=False) mobile_verification_code = models.CharField(('Mobile verification code'),max_length=12,blank=True, null=True) """ Form 2 fields""" business_name = models.CharField(('Business name'),max_length=20,blank=True, null=True) pincode = models.CharField(('Vendor pincode'),max_length=10,blank=True,null=True) city … -
Can't get celery working with Django using the cache backend and memory broker
These are the settings I'm using: CELERY_BROKER_URL='memory://' CELERY_BROKER_BACKEND = 'memory' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'django-cache' The celery worker starts but has nothing listed next to the results: line. When I call delay on a shared_task there's no reaction from the worker and the result always has a state of pending. Not really sure what to do. Does the memory broker just not work? -
getting an error not related to form validation
I am trying to inject the id (brand_id) from the previous website into a form, due to the fact that the object i am trying to create on the DB depends on that foreignkey relationship. Here's the code from brand.models import Brand from .models import Campaign from .forms import CampaignForm # Create your views here. def campaign_create(request): previous_website = request.META['HTTP_REFERER'] brand_id = int(previous_website.rsplit('/', 1)[-1]) print(brand_id) brand_object = Brand.objects.get(id=brand_id) # if not request.user.is_staff or not request.user.is_superuser: # raise Http404 title = "Create Campaign" form = CampaignForm(request.POST or None) # check whether it's valid: if form.is_valid(): #Checking that form is valid instance = form.save(commit=False) # saving the form as an instance object instance.user = request.user instance.brand = brand_object #adding the brand object instance.save() # saving in the database # redirect to a new URL: return HttpResponseRedirect(instance.get_absolute_url()) context = { "form": form, "title": title, } return render(request, "campaign_form.html", context) Outside the code (in shell), this works flawlessly, the issue is when I try to submit the code, although I get the correct ID number (prints the correct value in log) and i get the correct brand_object, I am getting a ValueError ValueError at /dashboard/campaign/create/ invalid literal for int() with base 10: '' since … -
many to many relationship between multiple tables using django
I have two tables borrower and lender,borrower can request many lenders and lenders also can get multiple requests from borrowers,so I want to give many to many relation between two of this example code: class borrower(models.Model): name=models.CharField(max_length=20) class lender(models.Model): city = models.CharField(max_length=20) now in the loanrequest table i want to define many to many relation between these two tables -
MySQL Connector not working | Django 1.10 | Windows | Python 3.5
For many months now I've been wanting to use MySQL and all of it's awesomeness for my django python website but keep running in to the same error. I've installed and reinstalled the official Oracle MySQL connector (https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html) and various packages like MySQLClient from the fork (http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysqlclient) which gives me a error. Wheel not supported When I utilize the back-end code specified on the docs page for the MySQL connector I get the same error in the server window. ImportError: No module named 'mysql' In my settings.py, this is the line where it errors out, attempting to import imort os import mysql.connector #this is where it errors out Pages I've looked at: - stackoverflow.com/questions/37848035/mysql-connector-python-as-django-engine - stackoverflow.com/questions/26573984/django-how-to-install-mysql-connector-python-with-pip3 - docs.djangoproject.com/en/1.10/ref/databases/ and many more. Please help. -
Django, let QuerySet methods to handle both queryset and list?
This has been haunting me for a long time and I couldn't find an answer for it. I'm not sure how QuerySet is cached in general, but prefetch_related is cached as a list. If you want to further filter the prefetch_related, you either run a new prefetch_related query, or you can filter it on python level. Sometimes it makes sense to do it the second way (filtering on python level) when it is expensive to run the query. QuerySet's method works on queryset and returns queryset, but it's advantageous to work with prefetched cache (I want to do this not just for prefetch_related but queryset in general if possible). I can think of something like, class Foo(models.Model): @property def bars(self): if hasattr(self, 'bar_set_prefetched'): return self.bar_set_prefetched else: return self.bar_set.all() class BarQuerySet(QuerySet): def is_visible(self): if prefetched: # don't know how to detect return [bar for bar in self if bar.visible] return self.filter(is_visible=True) class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='bar_set') visible = models.BooleanField(default=True) # client code foos = Foo.boejcts.prefetch_related( Prefetch( 'bars', to_attr='bar_set_prefetched' ) ) for foo in foos: bars = foo.bars.is_visible() # I want is_visible to use prefetched list instead of running new query I'm not sure if its doable and want to know … -
Django - turn field into tags with dropdown
In my form on django, I have a field called package_includes and a field called price. Right now, the content in package_includes it is simply text. So if I input "paper, glue, glitter" it will display exactly as i typed it, unable to change anything. However, I want the text to work like individual tags ->How I want tags to look So when you click on one of the individual items (EX: "paper", "glue", or "glitter") i want it to display a drop down that allows you the option to put extra glitter for an additional $2.00 to the total. Also, at the end of the text I want a tag that displays "Add" and this function would allow you to add items not included in this specific package. For example, you should be able to add crayons for $5, highlighter for $2.50, etc. I am new to programming and don't fully understand how to add a function to text like this in a field in django. Thank you in advance for your help! -
Django oauth2 responds with invalid client after months with successful use
For around 4-5 months I have been developing an IOS app with a django backend. For communication between both ends, I use django-oauth2-toolkit, which has worked fine. I created a clientID and clientSecret, which has until now worked (tokens are generated, and give users access to my servers resources). All of a sudden, access is now not possible, and instead I receive "invalid_client" responses from django. I honestly have no idea what to do here, as I'm fairly new to django, especially oauth2-toolkit. I would really appreciate any help. -
How can I get_or_create a unique model object when user submit a form?
I'm creating a private commenting system between users from scratch and I need guidance, when an user submit a form the view should get_or_create a unique Room where only the connected user and the recipient can comment ot with each other. I don't understand how I can assemble my code to create this feature, here is the model I'm using : class Product(models.Model) name = models.CharField() creator = models.ForeignKey(User) ... class Room(models.Model): user = models.ForeignKey(Product) #unique url for each new room uuid_url = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.TextField() ... When user submit through this form POST this to the concerned function on the views. <form method="post" action="{{ url 'new_room_detail' }}"> <input type="hidden" value="{{ product.id }}"> <input type="submit" value="Contact this user"> </form> views.py, Here is where I'm lacking knowledge (see code down there for explanation) : def new_room(request): try: #get the submited product object product = Product.objects.get(id=request.POST.get('product_id')) except Gig.DoesNotExist: return redirect('/') #if it's the first time that the connected user submit product.id to product.creator #then create OR get if it already exist, a Room with a unique url #in which only request.user and product.creator can comment. return redirect(reverse('commenting_room')) def commenting_room(request, uuid) ... I know there is already a get_or_create function … -
ServerSelectionTimeoutError when trying to integrate Django with Apache
Basically I was following this instruction: http://thecodeship.com/deployment/deploy-django-apache-virtualenv-and-mod_wsgi/ But result is: ServerSelectionTimeoutError at /admin/ No servers found yet Request Method: GET Request URL: http://52.25.226.143/admin/ Django Version: 1.5.11 Exception Type: ServerSelectionTimeoutError Exception Value: No servers found yet Exception Location: /home/ubuntu/.virtualenvs/venv/lib/python2.7/site-packages/pymongo/topology.py in select_servers, line 189 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/ubuntu/.virtualenvs/venv/lib/python2.7/site-packages', '/home/ubuntu/gitrepo/RIGIT/RIGIT_Backend', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/home/ubuntu/.virtualenvs/venv/local/lib/python2.7/site-packages', ...'] Server time: Fri, 27 Jan 2017 20:05:17 -0600 Did I miss something simple? -
Django elegant way to query if string field is a substring of string
To clarify, I'm not asking for Article.objects.filter(headline__in=['Doge', 'Cat', 'Lizard']) instead I want to do it the other way around. Kinda like this logic q = Q() for word in headline.split(): q |= Q(keyword_icontains=word) Keywords.objects.filter(query).all() Something akin to that. I'm not sure if there's a shortcut or maybe some sort of function that gives me access to what I need. -
Use Django's models in a Scrapy project (in the pipeline)
This has been asked before but the answer that always comes up is to use DjangoItem. However it states on it's github that: often not a good choice for a write intensive applications (such as a web crawler) ... may not scale well This is the crux of my problem, I'd like to use and interact with my django model in the same way I can when I run python manage.py shell and I do from myapp.models import Model1. Using queries like seen here. I have tried relative imports and moving my whole scrapy project inside my django app, both to no avail. Where should I move my scrapy project to for this to work? How can I recreate / use all the methods that are available to me in the shell inside a scrapy pipeline? Thanks in advance. -
reverse_lazy not matching with kwargs
I have a Django CreateView that is supposed to redirect to a URL with a UUID in the querystring: @method_decorator(xframe_options_exempt, name='dispatch') class ActivityCreateView(CreateView): template_name = 'embedded/activities/create.html' form_class = ActivityCreateUpdateForm def get_success_url(self): return reverse_lazy('embedded:activity_status', kwargs={'unieke_code': self.object.access_link}) This however gives the familiar error: Reverse for 'activity_status' with arguments '()' and keyword arguments '{'unieke_code': UUID('470e3a5f-6f52-414e-a431-bf5c6e68509a')}' not found. 1 pattern(s) tried: ['embedded/activiteiten/status/'] The weird thing is that it apparently finds the pattern, but still doesn't match. This is my urls.py: urlpatterns = [ url(r'^activiteiten/$', views.ActivitiesIndexView.as_view(), name='activities_index'), url(r'^activiteiten/aanmelden/$', views.ActivityCreateView.as_view(), name='activity_create'), url(r'^activiteiten/status/', views.ActivityStatusView.as_view(), name='activity_status'), ] Strangely enough when I go to mysite.com/embedded/activiteiten/status/?unieke_code=470e3a5f-6f52-414e-a431-bf5c6e68509a it does work. Full traceback: https://gist.github.com/voodoo-burger/4a5355bd39d50348e429fc091d0554eb . -
NoReverseMatch at Error using Django and D3
I'm trying to create a graph in d3 using django 1.5 (I can't upgrade it to the newer version). The logic is the following go to localhost:8000/usage/graphs This will load the html file (graphs.html) which will call another view The View ('use_count_by_month') produces data that is passed to the html page as a list of dictionaries I can confirm the view exports a dictionary, but I can't get the html to load the data. Error Msg: Reverse for ''use_count_by_month'' with arguments '()' and keyword arguments '{}' not found. This is my code: urls.py urlpatterns=patterns('usage.views', url(r'^graph/', 'graph', name='graph'), url(r'^use_count_by_month$/', 'use_count_by_month', name='data') ) views.py def graph(request): return render(request,'usage/graph.html') def use_count_by_month(request): data=[{"count_items": 731, "month": "2014-01-01"}, {"count_items":404, "month": "2014-02-01"}] json_string=json.dumps(data) return HttpResponse(json.dumps(data), content_type="application/json") From the html file... d3.json("{% url 'use_count_by_month' %}" ,function(error, data) { data.forEach(function(d) { d.month = parseDate(d.month); d.count_items = +d.count_items; }); -
OSError: [Errno 2] No such file or directory: '/tmp/MakeCalls/Static'
When doing 'git push heroku master' (from a Django app), the push gets rejected. I've included the traceback below. I can disable the collectstatic but then all the static files are missing from the webpage. When I run python manage.py collectstatic --noinput on my localserver it does not give any errors. I've spent the past two days on this, not sure what I'm doing wrong. I've included my .settings below for the staticfiles. I am using whitenoise which works perfectly fine on my localhost. I think it has to do with a relative path that is not found. But that can't be it because there are no errors on my local server? remote: $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 10, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 176, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/staticfiles/finders.py", … -
Django Postgres DateRangeField - can I use UNIQUE vaildator
I'm trying to use some of the shiny new Postgres fields in Django. For a booking system the DateRangeField seems perfect. Can I use the validators UNIQUE or even UNIQUE_DATE in regard to this field? The excellent Django documentation is, unfortunately, not elaborating regarding validators and the Postgres fields. -
Django Custom User Model ForeignKey Addition Not Showing in Admin
I've successfully created my own extension for the User model based on this tutorial: https://docs.djangoproject.com/en/dev/topics/auth/customizing/#custom-users-and-permissions I also need to add a ForeignKey to a Company model, so that each user is assigned to a company. But this isn't showing in the admin at all, neither in the initial admin view or the edit view. I've added the ForeignKey reference in the MyUser class like so: class MyUser(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) date_of_birth = models.DateField() company = models.ForeignKey('Company', on_delete=models.CASCADE, default=1) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['date_of_birth'] ... -
How can I convert plain text password into PBKDF2 algorithm format in Django?
I have list user information that I am pulling from some other database tool. The information in this tool is in plain text. I am using Django for my project and I need passowrd into <algorithm>$<iterations>$<salt>$<hash> format. Which library or script that I can use to convert my plaintext to Hashed value ? I have read about Django Hasher but wanted to get more information about it. -
Overwrite django choices output in graphene
I'm working with graphene y graphene-django and I have a problema with a IntegerField with choices. graphene create an Enum and the output is "A_1" if the value is 1; "A_2" if the value is 2 and so on. Example: # model class Foo(models.Model): score = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))) # query query { foo { score } } # response { "data": { "foo": { "source": "A_1" } } } I found a function that convert the choices values. def convert_choice_name(name): name = to_const(force_text(name)) try: assert_valid_name(name) except AssertionError: name = "A_%s" % name return name And assert_valid_name has this regular expression: r'^[_a-zA-Z][_a-zA-Z0-9]*$' Therefore, whatever begins with number, it will convert it to "A_...". How I can overwrite this output? Thanks. -
Unable to run Django server from PyCharm
Whenever I try to run a Django project from PyCharm, I get the following message. Process finished with exit code -1073741819 (0xC0000005) It happens whether I use the run button or the runserver command from the manage.py utility in PyCharm. If I run manage.py runserver from my OS command prompt it works. -
Pressing enter or return on keyboard doesn't save the list_editable - Django Admin
When I try to change the hours and press enter/return on the keyboard, it says in an alert dialog box, "You have unsaved changed on individual editable fields. If you run an action, your unsaved changes will be lost." probably because pressing enter presses the go button next to action rather than the save button. How can I make it so pressing enter while a field is selected presses the save button and submits the updated hours? The biggest reason I want to fix this is because many people will be annoyed with it not working and possibly erasing all the changes made if they press OK to the dialog box. -
Django - Filter ForeignKey drop down menu in inline formsets
I have the following models: models.py class Train(models.Model): pass class City(models.Model): train = models.ForeignKey(Train) name = models.CharField(max_length=100) class Route(models.Model): train = models.ForeignKey(Train) name = models.CharField(max_length=100) class Travel(models.Model): train = models.ForeignKey(Train) current_city = models.ForeignKey(City, related_name = 'current') through = models.ForeignKey(Route) next_city = models.ForeignKey(City, related_name = 'next') and I'm using inline formsets to create Travel instances related to a specific train with the following: views.py class TrainInfoUpdate(UpdateView): model = Train fields = [] success_url = reverse_lazy('train-list') def get_context_data(self, **kwargs): data = super(TrainInfoUpdate, self).get_context_data(**kwargs) if self.request.POST: data['travels'] = TravelFormSet(self.request.POST, instance=self.object) else: data['travels'] = TravelFormSet(instance=self.object) return data def form_valid(self, form): context = self.get_context_data() travels = context['travels'] with transaction.atomic(): self.object = form.save() if travels.is_valid(): travels.instance = self.object travels.save() return super(TrainInfoUpdate, self).form_valid(form) This gives me dropdown menu with all the cities and routes available but I would like to limit them to only the cities and routes related to that train, how can I achieve that? -
Upload multiple images in django
I have models like: class Gallery(models.Model): title = models.CharField(max_length=200) date = models.DateField(auto_now_add=True) author = models.ForeignKey(User, blank=True) class GalleryImage(models.Model): gallery = models.ForeignKey(Gallery, on_delete=models.CASCADE, related_name='image_in_gallery') image = models.ImageField(upload_to='gallery/%Y/%m/%d') title = models.CharField(max_length=200) How can I upload multiple images to Gallery, I mean using forms. -
Returning username in django 1.10 drf jwt response
I've been fiddling around with JWT_PAYLOAD_HANDLER trying to get a username returned in the output So I tried this in my myApp/views.py: def jwt_response_payload_handler(token, user=None, request=None): if user and request: return json.dumps({ 'token': token, 'username': str(request.user.username) }) else: return { 'token': token } and then I tried this in my project/settings.py: JWT_AUTH = { 'JWT_PAYLOAD_HANDLER': 'myApp.views.jwt_response_payload_handler' } doing a curl request I get the error message: TypeError at /api-token-auth/ <User: nunya> is not JSON serializable I'm so close to figuring this out ... but I'm missing something. What am I missing?