Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calculate price in models with django v2.1
I need your help about this app I'm making, in those models, I want the price of the topping and the type be calculated automatic in the model Pizza, so when someone record new data, he can choice the type and the topping and the price is calculated and save it in that table Pizza. class Type(models.Model): typeName = models.CharField( max_length = 50 ) priceBase = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 ) obsBase = models.CharField( max_length = 200, null=True ) def __str__(self): return self.typeName class Topping(models.Model): nameTopping = models.CharField( max_length = 200) priceTopping = models.DecimalField( max_digits = 6, decimal_places = 0, default=0 ) obsTopping = models.CharField( max_length = 200, null=True ) def __str__(self): return self.nameTopping class Pizza(models.Model): namePizza = models.CharField(max_length=200) typePizza = models.ForeignKey(Type, on_delete=models.SET_NULL, null=True ) toppingPizza = models.ForeignKey(Topping, on_delete=models.SET_NULL, null=True) obsPizza = models.CharField(max_length = 200, null=True) def __str__(self): return self.namePizza Guys, can I use this logic to save my kind of pizzas in a database so I can retrive the calculated data when someone order a pizza online?, I'm starting with the right foot?, sorry I'm new at django, and I'm trying to learn everything on the web, and your help will be precious for me! … -
Is it possible to limit the number of messages a user can send a day?
I have been using Django Postman for a few weeks now, and in order to limit the number of messages sent by each user, I have been wondering what would be the best way to limit the number of messages a user can send a day, a week... using Django-postman? I have been browsing dedicated documentation for weeks too in order to find an answer for the how, but I think this is not a usecase for now, and I do not really know how to manage that. Of course I am not looking for a well cooked answer, but I would like to avoid writing labyrinthine code, so maybe just a few ideas about it could help me to see clear through that problematic. Many thanks for your help on that topic! -
Display the fruit's name with the same ID as user's in Django
sorry for the weird example. I have 2 apps : accounts & fruits. Let's say that the user can have 1 fruit and it's showed in his class 'Profile' as 'fruit'. (FRUIT_CHOICES is the ID of the fruit). fruit = models.IntegerField(choices=FRUIT_CHOICES) Now that the User got the fruit's ID in possession, I would like to take more informations from this. So, just after, I write this : user_fruit = Fruit.objects.filter(id = fruit) And here's what I get : django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. How can I fix that ? Thanks ! -
Django how to capture an already changed file name
This is an admin form handler, for example I upload a test.txt file in the django admin panel: def save_model(self, request, obj, form, change): if 'torrent_file' in form.changed_data: print("file has changed: ") print(obj.torrent_file) else: print("file has not changed") super(FileAdmin, self).save_model(request, obj, form, change) here i get the original file name from the upload form, but by fact the file is saved with another name if there is already a file with this name, but in the above code i get only the original name in all cases, how to can I get the changed/updated file name that was saved? -
Error initialising model with UUIDField django
Problem : So, I have been trying to make an object of the model Trade with an initial value to the identifier from my custom function gen_rand_string(). But the problem is when, I am initialising it. If I remove the initializer and set the UUIDField to NULL, it works out to be fine. This is the error, I am getting : TypeError at /admin/account/trade/add/ int() argument must be a string or a number, not 'Trade' My Trade class : class Trade(models.Model): NEW_TRADE = 'N' CANCELLED_TRADE = 'C' PENDING_TRADE = 'P' STATUS_OF_TRADE = ( (NEW_TRADE, "New"), (CANCELLED_TRADE, "Cancelled"), (PENDING_TRADE, "Pending") ) TYPE_BUY = 'B' TYPE_SELL = 'S' TYPE_OF_TRADE = ( (TYPE_BUY, "Buy"), (TYPE_SELL, "Sell") ) user = models.OneToOneField('UserProfile', related_name='trades') identifier = models.UUIDField(null=False, editable=False) created_at = models.DateTimeField(auto_now_add=True, editable=False) finished_at = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=19, decimal_places=10, null=False) type = models.CharField(max_length=2, choices=TYPE_OF_TRADE, null=False) status = models.CharField(max_length=2, choices=STATUS_OF_TRADE, default=PENDING_TRADE, null=False) def __init__(self, *args, **kwargs): self.identifier = gen_rand_string() super(Trade, self).__init__(self, *args, **kwargs) class Meta: ordering = ('created_at',) def __unicode__(self): return self.identifier def __str__(self): return self.identifier My gen_rand_string() : def gen_rand_string(purpose=''): if purpose: return purpose + '_' + get_random_string(length=64 - len(purpose)) else: return get_random_string(length=64) Suggestions : I am making a random string for each trade in not … -
Django blog application error
I have just started coding with django module and for now i am just copying a code from lynda. Although i coded correctly, i got tons of error when i tried to run server. I guess it is because of differences between Django 2 and Django 1.8. What exactly should i change? You may find my code and errors below. Thanks. Errors: python manage.py runserver Performing system checks... Unhandled exception in thread started by .wrapper at 0x105a53598> Traceback (most recent call last): File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/urls/conf.py", line 17, in include urlconf_module, app_name = arg ValueError: too many values to unpack (expected 2) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 121, in inner_run self.check(display_num_errors=True) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/utils/functional.py", line 36, in get res = instance.dict[self.name] = self.func(instance) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/urls/resolvers.py", line 536, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/keremkizbaz/anaconda3/lib/python3.6/site-packages/django/utils/functional.py", line 36, in … -
django-ckeditor doesnt save changes IN CKEditor widget
I have integrated django-ckeditor into my admin and everything is working. The only issue I have is when I use googlewebfontsplugin the changes are made to the content, so it is working , but when i reload the admin page the ckeditor widget prepopulates without the changes I just made. I think this is a problem with the googlewebfonts plugin since when I change the font size, type or style, the ckeditor widget prepopulates correctly with any changes I make, but it seems when I use the googlewebfonts plugin the changes arent made and it resets to normal. config.js : CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.font_names = 'GoogleWebFonts'; config.extraPlugins = 'ckeditor-gwf-plugin'; 'pbckcode'; config.toolbarGroups = [ {name: 'pbckcode'},] }; settings.py : CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', 'height': 300, 'width': 900, }, } Thank you for any help. -
Django upload csv file copt to postgresql table
I am uploading a csv file in Django : $('#import-file-dialog').on('change', function(event) { $('#upload-files').click(); }); <div class="" style="padding-left: 15px;"> <button class="btn btn-primary btn-outline" id="open-file-dialog">Upload Bulk</button> <input type="file" id="import-file-dialog" name="import_file_dialog" style="display: none;" /> <button class="btn btn-primary" id="upload-files" name="upload_import" style="display: none;">Upload Bulk</button> </div> And after in Django View: import_data = request.FILES.get('import_file_dialog') file = import_data.read() Now i want to use psycopg2 copy_from for inserting csv data to Posgresql. I do google for same but unable to get exact answer. I had two problem 1- Remove header from csv data 2-Use copy_from to insert that csv data to postgresql. Thanks for your precious time. -
How to use opencv in django to capture images?
I am making a web app in python using DJANGO. I want to make a window in my webpage that will display the feed from my webcam using OPENCV and i can take picture through it. OPENCV displays feed in a desktop window by using IMSHOW() but i want to show it in my webpage somehow. -
Redirecting to the required page but url is not changing in django
I have created a small django project. In that when i try to redirect to a specific page, the url is not changing but the required page is getting loaded properly. I am using render() to redirect to the specific pages. views.py file: def create_album(request): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] album.save() return render(request, 'photo/detail.html', {'album': album}) context = { "form": form, } return render(request, 'photo/create_album.html', context) def detail(request, album_id): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: user = request.user album = get_object_or_404(Album, pk=album_id) return render(request, 'photo/detail.html', {'album': album, 'user': user}) urls.py file: from django.conf.urls import url from . import views app_name = 'photo' urlpatterns = [ url(r'^login_user/$', views.login_user, name='login_user'), url(r'^register/$', views.register, name='register'), url(r'^logout_user/$', views.logout_user, name='logout_user'), url(r'^(?P<album_id>[0-9]+)/$', views.detail, name='detail'), url(r'^create_album/$', views.create_album, name='create_album'), url(r'^(?P<album_id>[0-9]+)/create_picture/$', views.create_picture, name='create_picture'), url(r'^(?P<album_id>[0-9]+)/delete_album/$', views.delete_album, name='delete_album'), url(r'^(?P<song_id>[0-9]+)/favorite/$', views.favorite, name='favorite'), url(r'^(?P<album_id>[0-9]+)/favorite_album/$', views.favorite_album, name='favorite_album'), url(r'^(?P<album_id>[0-9]+)/delete_pic/(?P<song_id>[0-9]+)/$', views.delete_pic, name='delete_pic'), url(r'^$', views.index, name='index'), ] The problem is when i try to create an album, i get the url as:127.0.0.1:8000/create_album/ After creating the album, the page has to redirected to detail.html page. The url for that should be:127.0.0.1:8000/10/ (10 is the album_id) But the … -
ValueError: Cannot assign "u'http://localhost:8000/players/1/'": "Game.referee" must be a "User" instance
I understand what this error is saying, just not understanding how to pass user instance in a request(postman). Following is my model. class Game(models.Model): referee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='referee') player_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='opponent_1') player_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='opponent_2') attacker = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attacker') status = models.CharField(max_length=20, choices=GAME_STATUS, default='QUEUED') game_type = models.CharField(max_length=20, choices=GAME_TYPE, default='LEAGUE') serializer. class GameSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Game fields = ('__all__') and viewset is class GameViewSet(viewsets.ModelViewSet): queryset = Game.objects.all() serializer_class = GameSerializer Till here "u'http://localhost:8000/players/1/'" works fine. As soon as I do following . def create(self, request): game = Game.objects.create( referee = request.data.get('referee', request.user), player_1 = request.data.get('player_1', None), player_2 = request.data.get('player_2', None), attacker = request.data.get('attacker', None), status = request.data.get('status', None), game_type = request.data.get('game_type', None) ) game.save() return game the same API call throws following error ValueError: Cannot assign "u'http://localhost:8000/players/1/'": "Game.referee" must be a "User" instance. Should I really create user instance from the url or there is more elegant way to pass the user instance? -
How to show mp3 player in django
I have a question. I want to have on my website a mp3 player. I made somethink like this: models.py class Wpisy(models.Model): title = models.CharField(max_length=400, verbose_name="Tytuł") slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url") content = models.TextField() status_audio = models.BooleanField(default=False, verbose_name="Czy dostępny będzie plik audio?") audio_file = models.FileField(upload_to='uploads/',verbose_name="Plik audio") created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia") category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE) and i have also in html file the code : {% extends 'bajki/index.html' %} {% block content %} Utworzono : {{detale_bajki.created_date}}<br> Kategoria: {{detale_bajki.category}}<br> {{ detale_bajki.title }}<br> {{ detale_bajki.content}}<br><p> {% if detale_bajki.status_audio == True %} <audio controls> <source src="/uploads/{{ audio_file.url }}" type="audio/mp3"> Twoja przeglądarka nie obsługuje plików audio. </audio> {% else %} {% endif %} {% endblock %} the mp3 player in html is visible on the page but play nothing. In admin mode i'v added a mp3 song in the few of records but still nothing. Also I'v created in settings.py the lines : MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') MEDIA_URL = '/uploads/' -
How can I access objects in a django model composed of two foreign keys?
These are the relevant classes of my app. I want basically understand if the a certain user (form AuthUser) is linked to a business (from BusinessInformation) by looking at UserBusinessInformation. Thanks class AuthUser(models.Model): password = models.CharField(max_length=128) last_login = models.DateTimeField(blank=True, null=True) is_superuser = models.IntegerField() username = models.CharField(unique=True, max_length=150) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.CharField(max_length=254) is_staff = models.IntegerField() is_active = models.IntegerField() date_joined = models.DateTimeField() class Meta: managed = False db_table = 'auth_user' class BusinessInformation(models.Model): business_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lat = models.CharField(max_length=255) lng = models.CharField(max_length=255) formatted_address = models.CharField(max_length=255, blank=True, null=True) locality = models.CharField(max_length=255, blank=True, null=True) country = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_5 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_4 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_3 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_2 = models.CharField(max_length=255, blank=True, null=True) administrative_area_level_1 = models.CharField(max_length=255, blank=True, null=True) postal_code = models.CharField(max_length=45, blank=True, null=True) route = models.CharField(max_length=255, blank=True, null=True) street_number = models.CharField(max_length=45, blank=True, null=True) phone = models.CharField(max_length=255, blank=True, null=True) phone2 = models.CharField(max_length=255, blank=True, null=True) phone3 = models.CharField(max_length=255, blank=True, null=True) email = models.CharField(max_length=255, blank=True, null=True) email2 = models.CharField(max_length=255, blank=True, null=True) email3 = models.CharField(max_length=255, blank=True, null=True) website = models.CharField(max_length=255, blank=True, null=True) facebook = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'business_information' class UserBusinessInformation(models.Model): user = models.ForeignKey(AuthUser, models.DO_NOTHING) business = models.ForeignKey(BusinessInformation, models.DO_NOTHING) … -
How can you use Django filters for string search when searching for some slightly different keywords in two models?
I came across a situation where I get two name in two model for a same product.The product are named as Xiaomi Redmi Note 3 in one model and Xiaomi Note 3 in another model. When I conduct a search to both model with filter __icontains with the keyword Xiaomi Note i get results from my second model but not from the first one. How can i get results from both model with this keyword. -
Unable to cast string to float to update a PointField
I'm trying to update a user's PointField but receive errors of TypeError('Invalid parameters given for Point initialization.') I may be going about this wrong as the other questions on SO regarding updating a PointField don't seem to address this issue at all--I haven't found any examples where users first cast their string to a float in order to update the pointfield. What's the proper way to save the PointField? Here's what I'm trying: from django.contrib.gis.geos import Point class LocationAjaxView(View): def get(self, request, *args, **kwargs): if self.request.is_ajax(): lat = self.request.GET.get('lat') lon = self.request.GET.get('lon') float(lat) float(lon) if self.request.user.is_authenticated: user = self.request.user Profile.objects.filter(user=user).update(last_location=Point(lat, lon)) return JsonResponse({'key': "value"}, safe=False) The relevant model field: ... last_location = models.PointField(null=True) ... I'm retrieving the lat and long coordinates via ajax. -
celery - message queues for long time running processes
I'm building a web server via django 1.11.5, that uses celery-3.1.23 & rabbitmq as message queue manager, to send async-tasks to a number of different demon-processes (processes with infinite loop [long time running]). How can I dynamically create queues for each process separately, and receive messages from the process' queue inside the daemon-process, do something asynchronously, and then forward the result to another "aggregator queue", to collect & validate the results, and sending a response to the user. (please see attached ilustracion) So far, I connected the processes via multiprocessing.connection Client and Server objects, and opened the processes by the Process object. code - consumer: from multiprocessing.connection import Listener from multiprocessing import Process def main_process_loop(path, port_id, auth_key): # Initialize the action1 intance to handle work stream: action_handler = ActionHandler(path) # Initialize the infinite loop that will run the process: pid, auth_key_bytes = int(port_id), bytes(auth_key) address = ('localhost', pid) # family is deduced to be 'AF_INET' while True: try: listener = Listener(address, authkey=auth_key_bytes) conn = listener.accept() input_values = conn.recv() listener.close() if input_values == None: raise Exception(ERR_MSG_INVALID_ARGV) else: #do something with input_values and ActionHandler # need to return success message to user except Exception as err: # need to return fail message … -
heroku not loading js files in django app
I tried deploying my django app on heroku, it works fine when i do heroku open, but when i click on buttons or some glyphicons they doesn't seem to work.The js files and bootstrap cdn js files are not being loaded.The css files are working fine though I tried python manage.py collectstatic as well.It didn't throw any error. My settings.py : import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) db_from_env = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(db_from_env) # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ STATIC_URL = '/static/' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') Requirements.txt: Django==1.11.6 dj-database-url==0.4.2 django-taggit==0.22.1 gunicorn==19.7.1 Pillow==3.1.2 Markdown==2.6.9 psycopg2==2.7.1 whitenoise==3.3.1 How can i solve this problem.Thanks -
Display the user's username when displaying their row from a seperate database table
On my website, I have a page where I display all my user's profiles (containing info such as bio, location etc). This data is NOT stored in my 'User Model' but in a model named 'Profile'. Obviously, I display this information like this: views.py queryset_list = Profile.objects.all() template {% for Profile in queryset_list %} {{Profile.bio}} {% endfor %} I also want to display these user's 'usernames' (which is stored in the User Model, NOT the Profile Model) but I don't know how to reference the User Model in relation to the Profile Model to get the connected username. Any help would be much appreciated. -
How to save ordered multiple upload files in Django
I have a Django form to upload multiple images. With Javascript, I allow user to see files name and sort it using sortable.min.js library before submit the form. It's possible to save the files using the order the user gives? last_position = property.images.last().position for index, item in enumerate(self.request.FILES.getlist('image'), start=last_position + 1): i = Image(prop=property, image=item, position=index) i.save() -
slug as detail view in django
I have a little problem. I want to use slug as a detail view in my project. But I don't know what I must change. My project files are models. py from django.db import models from django.utils import timezone class Kategorie(models.Model): title = models.CharField(max_length=250, verbose_name="Kategoria") slug = models.SlugField(unique=True, max_length=250, verbose_name="Przyjazny adres url") class Meta: verbose_name="Kategoria" verbose_name_plural="Kategorie" def __str__(self): return self.title class Wpisy(models.Model): title = models.CharField(max_length=400, verbose_name="Tytuł") slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url") content = models.TextField() created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia") category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE) class Meta: verbose_name="Wpis" verbose_name_plural="Wpisy" def __str__(self): return self.title urls.py from django.urls import path from . import views urlpatterns = [ path('', views.lista_bajek, name="lista_bajek"), path('bajki/',views.lista_bajek, name='lista_bajek'), path('bajki/(?P<pk>\d+)/$', views.detale_bajki, name='detale_bajki'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Wpisy def lista_bajek(request): lista_bajek = Wpisy.objects.all() context ={'lista_bajek': lista_bajek,} return render(request, 'bajki/lista_bajek.html', context=context) def detale_bajki(request, pk): detale_bajki = get_object_or_404(Wpisy, pk=pk) return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki}) the one of html file {% extends 'bajki/index.html'%} {% block content %} <!DOCTYPE html> <html> <head> <title>Bajki</title> </head> <body> {% for bajki in lista_bajek %} Tytuł : <a href="{% url 'detale_bajki' pk=bajki.pk %}">{{bajki.title}} </a><br> {% endfor %} {% endblock %} </body> </html> Can somebdy tell me what I must to change … -
how can set a default value for MultiSelectField of a django model
from django.db import models from multiselectfield import MultiSelectField class Shop(models.Model): DAYS = ( ('sunday', 'Sunday'), ('monday', 'Monday'), ('tuesday', 'Tuesday'), ('wednesday', 'Wednesday'), ('thursday', 'Thursday'), ('friday', 'Friday'), ('saturday', 'Saturday'), ('Not any day', 'None'), ) closingDay = MultiSelectField(choices=DAYS) click here to get picture -
Celery + Sqs. Worker suddenly crash
I use SQS as broker for celery. When I start worker, it suddenly shutdown. My configs BROKER_URL = 'sqs://XXX:YYY@' BROKER_TRANSPORT_OPTIONS = { 'region': 'us-east-1', 'queue_name_prefix': 'dev-' } CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_CONTENT_ENCODING = 'utf-8' CELERY_QUEUES = ( Queue('high', Exchange('high'), routing_key='high'), Queue('low', Exchange('low'), routing_key='low'), ) When i start celery i see: [2018-01-21 15:05:17,193: INFO/MainProcess] Starting new HTTPS connection (1): queue.amazonaws.com [2018-01-21 15:05:17,889: INFO/MainProcess] Connected to sqs://XXX:**@localhost// [2018-01-21 15:05:17,932: INFO/MainProcess] Starting new HTTPS connection (1): queue.amazonaws.com After it worker stops Installed packages: boto3==1.5.19 botocore==1.8.33 celery==4.1.0 crypto==1.4.1 kombu==4.1.0 pycrypto==2.6.1 pycurl==7.43.0.1 -
URL is not changing though page redirects in django
I have developed a simple django project in which photos will be stored and displayed. The problem is whenever I redirect to a page, the page gets loaded but the url does not change in the address bar. So when i refresh the page again, I am getting errors. For example, I created an album. For that the url is: 127.0.0.1:8000/create_album/ Then it has to redirect to the albums page where all albums of user are stored. That url is 127.0.0.1:8000/10/ But i am not getting that url when i redirect to that page. The views.py: **def create_album(request): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: form = AlbumForm(request.POST or None, request.FILES or None) if form.is_valid(): album = form.save(commit=False) album.user = request.user album.album_logo = request.FILES['album_logo'] album.save() return render(request, 'photo/detail.html', {'album': album}) context = { "form": form, } return render(request, 'photo/create_album.html', context) def detail(request, album_id): if not request.user.is_authenticated(): return render(request, 'photo/login.html') else: user = request.user album = get_object_or_404(Album, pk=album_id) return render(request, 'photo/detail.html', {'album': album, 'user': user})** The page has to be redirected to photo/detail.html. It redirects to the required page but the url doesn't change. Please help me with this. -
Removing the primary key in class based views ( django rest framework )
Problem : Currently in my api/urls.py I have this line url(r'^profile/(?P<pk>[0-9]+)/$', views.UserProfileView.as_view()), but I want to get the profile based on request.user and so I have the code in class UserProfileView as the following : class UserProfileView(generics.RetrieveUpdateAPIView): serializer_class = UserProfileSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly,) pagination_class = LimitTenPagination def get_queryset(self): try: queryset = UserProfile.objects.filter(user=self.request.user) except: raise APIException('No profile linked with this user') return queryset But If I remove the pk field from urls.py file, I get an error like this : AssertionError at /api/profile/ Expected view UserProfileView to be called with a URL keyword argument named "pk". Fix your URL conf, or set the .lookup_field attribute on the view correctly. Which is expected. Possible solution : I made a function based view like this : @api_view(['GET', 'PUT']) def user_detail(request): """ Retrieve, update or delete a code snippet. """ try: user_profile_data = UserProfile.objects.get(user=request.user) except: raise APIException('No profile linked with this user') if request.method == 'GET': serializer = UserProfileSerializer(user_profile_data) return Response(serializer.data) elif request.method == 'PUT': serializer = UserProfileSerializer(user_profile_data, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) And in the urls.py file added this line : url(r'^me/$', views.user_detail), This gets the work done, but I want a class based solution, so that in … -
How to get currency symbol from ISO country code in Django application?
I just want to get the Currency symbol for different countries in my Python Django application from the country code I have. For example I have a country code 'US', the output I need is '$' or 'US$'. Now I achieve this with the help of two libraries, namely pycountry and forex-python. Can I achieve this in a more simple way? import pycountry from forex_python.converter import CurrencyCodes code = "US" country = pycountry.countries.get(alpha_2=code) currency = pycountry.currencies.get(numeric=country.numeric) country_codes = CurrencyCodes() c.get_symbol(currency.alpha_3) Output: 'US$'